Repository navigation
Conversation
Adds datacatalog.cookcountyil.gov.yaml covering the Cook County State's Attorney felony case pipeline: intake, initiation, dispositions, sentencing, and diversion (~3.2M rows total). All five datasets are set to full_replace rather than the default incremental sync. Their rows are mutable — a charge's disposition and sentence are revised as a case moves through court — and the SAO republished them wholesale, so an incremental append keyed on :updated_at would accumulate stale duplicates instead of updating. Note these datasets were frozen by the SAO on 2024-12-30 and are no longer maintained; coverage runs 2011-01-01 to 2024-11-30. app_token is left commented out so the config validates without SOCRATA_APP_TOKEN set; anonymous sync works but is rate-limited. Also adds *.duckdb.lock to .gitignore. The existing *.duckdb pattern does not match the advisory lock files csq creates alongside each portal database, so they showed up as untracked. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Adds internal/modes, a registry of ready-to-run analysis profiles, plus a
`csq modes` subcommand. Bare `csq` now lists the modes, so they are the
first thing a new user sees.
Three modes ship:
corruption 8 datasets, 6 queries — contract concentration by vendor and
department, procurement type mix, lobbyist compensation,
contribution recipients, and the overlap between the two.
ranking 0 datasets, 6 queries — cross-portal comparison of breadth,
category coverage, sync coverage, and freshness.
police 7 datasets, 8 queries — COPA/BIA complaint volume, finding
and category outcomes, complainant demographics, officer
tenure, shootings, and beat distribution.
A mode is data, not a code path: adding one means appending to the
registry, not touching the CLI. Queries carry placeholder tokens that
expand at run time — {{P}} for the single attached portal, {{CATALOG}}
and {{SYNCRUNS}} for a UNION ALL across every portal, which is what lets
`ranking` work on any portal without per-city code.
Subcommands:
csq modes list
csq modes show <mode> datasets, queries, caveats
csq modes init <mode> emit a sync config for the mode's datasets
csq modes run <mode> execute the queries against attached DuckDBs
`modes run` ATTACHes every portal READ_ONLY, so it composes with a
running MCP server or sync holding the same file rather than contending
for the write lock. Nothing in this path writes.
Every dataset id was verified against the live Socrata API before being
hardcoded, and every query references only columns confirmed present in
the upstream schema.
Scope note: `ranking` compares open-data transparency, not livability or
governance. Outcome-based city ranking needs population denominators and
a mapping between incompatible per-city schemas, neither of which csq
has; emitting such a number would be inventing it.
Modes carry interpretation caveats as a structural requirement, not
documentation. They are printed by `modes show`, printed above `modes
run` output, embedded as comments in `modes init` YAML, and a test fails
the build if any mode declares none. Contract concentration is often
legitimate, and an unsustained complaint is not a false one; a tool that
reports on procurement and policing should say so where the numbers are.
Note for the police mode: Chicago's published COPA and BIA extracts carry
no officer identifier, so repeat-officer analysis is not possible with
them. That is recorded as the lead caveat rather than shipped as a query
that cannot work.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Adds a Modes section after the Quickstart, where it lands before the MCP setup — modes are the fastest onramp and they are what a bare `csq` invocation advertises. Covers the three shipped modes, the init/sync/run flow for modes that carry datasets, and the fact that `ranking` reads the _csq schema of databases you already built rather than syncing its own. States the two scope limits explicitly rather than leaving them to be discovered: `ranking` compares open-data transparency and not livability or governance, and `police` is civilian-side oversight whose upstream COPA/BIA extracts carry no officer identifier. Also notes that `modes run` attaches READ_ONLY and so composes with a running mcp or sync. Adds internal/modes to the Layout listing. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
The other three modes answer a civic question. This one asks whether the
data can bear the weight of an answer at all — the due-diligence pass
that belongs before a finding, not after it.
Cross-portal and dataset-less, like ranking: it audits whatever you have
already synced, reading only the _csq schema and DuckDB's catalog, so it
works on any portal without per-city code.
Eight queries in two groups. Provenance and coverage: successful syncs
with timings and config hash for citation, failed runs with their error,
and the gap between what a portal publishes and what you actually pulled.
Corpus profiling: schema inventory, candidate join keys, and every date
column that needs range-checking.
Two queries emit SQL rather than guessing at numbers they cannot compute
in a single pass — per-table SUMMARIZE, and a MIN/MAX check across every
date column. Generating SQL is the honest option here; the alternative
would be dynamic execution the user never sees.
Adds a {{ALIASES}} placeholder expanding to a quoted alias list, so
engine metadata functions like duckdb_columns() — which span every
attached database — can be scoped to just the portals the user asked
for. Without it these queries would silently report on databases the
user did not attach.
Verified against the live corpus: join-candidates independently recovers
case_id + case_participant_id as the keys across all five Cook County
tables, and the generated range checks surface a sentence_date reaching
the year 2921 and an arrest_date starting in 1915 — real upstream
defects that would otherwise reach a chart unnoticed.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Adds the freshness caveat to the README's scope limits. csq records when it last pulled a dataset, not when the city last updated it, so a dataset frozen upstream for years still reports a sync from this morning. This is the trap most likely to produce a confidently wrong claim about civic data, and it deserves to be visible before someone commits to a sync rather than a command away in `modes show research`. Cites the five Cook County State's Attorney datasets as the live example: frozen on 2024-12-30, covering through 2024-11-30, syncing cleanly today. The underlying cause is that _csq.catalog.updated_at is never populated — internal/socrata/catalog.go reads a `rowsUpdatedAt` key that the live /api/catalog/v1 response does not contain (it returns `updatedAt` and `data_updated_at`). Fixing that tag would let research report real upstream freshness instead of directing the reader to the portal. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
_csq.catalog.updated_at was NULL for every dataset on every portal.
rawCatalogEntry read a `rowsUpdatedAt` key that /api/catalog/v1 does not
return — that field name belongs to /api/views/{id}.json, so the tag was
almost certainly copied from the wrong endpoint. The parse block below it
was correct and simply never reached.
Reads data_updated_at first, falling back to updatedAt and then
rowsUpdatedAt so a views payload still resolves. Field order is the whole
point: on a 100-dataset Chicago sample, updatedAt equals
max(data_updated_at, metadata_updated_at) in every case and was later
than data_updated_at 48 times. Dataset 2ft4-4uik has data frozen since
2011 but an updatedAt of 2015, purely because someone edited its
description — reading updatedAt would report metadata churn as data
freshness.
Verified live rather than only in tests: refetching the Cook County
catalog takes updated_at from 0/808 populated to 808/808.
Why the suite missed this: catalog_test.go built a hand-written fixture
containing rowsUpdatedAt and asserted UpdatedAt was non-nil, so the test
passed against a response shape the API never produces. The fixture now
mirrors a real payload, and TestFetchCatalog_LiveResponseShape replays a
trimmed live response including the frozen-dataset case.
TestCatalogTimestampPrecedence pins the field order directly.
This narrows the freshness gap without closing it, and the README now
says so: data_updated_at still moves when a portal republishes unchanged
rows. The five Cook County State's Attorney datasets were abandoned on
2024-12-30 with coverage ending 2024-11-30, yet report 2026-04-02.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Moves the report out of session-scoped scratch and into the repo, so it is versioned alongside the code it describes and the fixes it tracks. Records seven defects from an unscripted end-to-end session — cold MCP install through a 3.17M-row sync to analytical querying — with repro steps, root cause at file:line, and suggested fixes. P2-1 is marked fixed (68ad3f2); P1-1 (MCP takes an exclusive write lock on read-only portals) and P1-2 (list_datasets fabricates table_name for never-synced datasets) remain open and are the two that matter. Includes a revision history, because the report is amended in place rather than reissued and one of its own Rev 1 claims turned out to be wrong: it asserted a working updated_at would have flagged the frozen Cook County datasets, which implementing the fix disproved. That correction is recorded rather than quietly patched. Also keeps a section disclosing operator errors that were not product defects, so the defect list can be read as the considered subset it is. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Two items from the accessibility plan. csq query — read-only ad-hoc SQL over one or more portals, with --format table|csv|json|parquet and --output. Until now there was no way to run arbitrary SQL or get data out of csq at all: no CSV, no Parquet, no COPY anywhere in the tree. A researcher had to install DuckDB separately just to ask a question, and had no path into R, pandas, or a paper. Portals attach READ_ONLY and the query runs inside BEGIN TRANSACTION READ ONLY; a CREATE is refused by the engine. With one --db that portal becomes the default so unqualified names resolve. mcpserver — OpenPools now takes the set of aliases that need write access, and opens everything else access_mode=read_only. Only portals with a registered config need read-write: their write tools reopen the same path in-process, and DuckDB will not hold one file at two access modes. Read-only portals never needed it — those pools only run hardcoded read queries. Scope correction on P1-1. The QA report claimed read-only pools would unblock a concurrent `csq sync`. Measured, they do not. DuckDB permits many readers or one writer, never both, so a writer is refused whichever mode the reader holds; serving and syncing one file at once is not reachable by changing access modes and needs snapshot-and-swap or a second file. What the change does fix is reader-reader contention: two servers, or a server plus a CLI session, can now share a portal where before the exclusive write lock made that impossible. Also note csq embeds DuckDB v1.4.3 while the v1.5.5 CLI is stricter about reader/writer overlap, which is why a `duckdb -readonly` session can attach to a file the server holds today. Tests: TestOpenPools_ReadOnlyByDefault asserts the engine refuses writes rather than trusting a flag, and TestOpenPools_ReadOnlyAllowsSecondProcess re-executes the test binary to prove a second process can attach. It has to be cross-process and must seed out-of-process too — DuckDB's instance cache keeps a file locked for the life of whichever process opened it read-write, so seeding in-process would leave the parent holding the very lock the test exists to prove absent. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
P1-1 is fixed in a100a6a, but implementing it disproved the entry's central claim. Rev 1 said read-only pools would let a csq sync run while a portal is served; measurement shows DuckDB permits many readers or one writer and never both, so a writer is refused whichever mode the reader holds. Serve-while-syncing is unreachable by access-mode changes and needs snapshot-and-swap. Severity drops to Medium because the workflow that justified High does not exist. What the fix does deliver — reader-reader concurrency for two servers or a server plus a CLI session — is stated in its place. Also qualifies a Rev 1 observation that had become misleading. The DuckDB CLI evidence was gathered across two engine versions (csq embeds v1.4.3, the CLI is v1.5.5) which differ on reader/writer overlap, so it never supported the concurrency conclusion drawn from it. It still shows read-only is the right privilege level, and the entry now says only that. Adds a cross-cutting note: both fixes so far were real defects whose stated consequence was wrong, and both were only caught by implementing and measuring. Impact claims should be treated as unverified until the fix is exercised, especially when they rest on assumed behaviour of a dependency. P1-2 is now the top open defect. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
list_datasets and describe_dataset synthesised a plausible table name from the dataset id whenever no successful sync existed, so a catalog-only portal advertised a concrete table_name for every entry it had never synced. On the Chicago database that was 2,010 datasets claiming tables against zero real ones. row_count was tagged omitempty, so the one field that would have exposed this was dropped from the payload rather than emitted as null. For a server whose consumers are LLM agents this is the worst shape of bug: not a missing capability but a confident false claim, which fails at query time with a binder error instead of at discovery time with an honest answer. TableName and RowCount are now *string and *int64 emitted without omitempty, so both appear as null, and a new synced bool states the fact directly. describe_dataset additionally stops probing information_schema for a table it invented and returns an empty column list instead. Verified live: listing the Cook County portal returns 808 datasets with exactly 5 non-null table_names, matching the 5 tables actually synced. The old behaviour was asserted as correct by TestListDatasets_NeverSynced_RowCountNil, which checked for the synthesised fallback — the bug was encoded in the suite, not overlooked by it. That test is replaced by one asserting the absence, plus a test pinning the wire format so table_name/row_count are present-and-null rather than omitted. Closes P1-2, the last of the two high-severity defects from docs/qa-report-2026-08-06.md. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Both tools returned every match unconditionally. On the Chicago portal a no-argument list_datasets produced a 351,820-character response — past what an agent can accept — which made the tool unusable in exactly the form an agent calls it first. query_sql has capped results at 1000 rows / 1MB / 30s since Phase 3; these two had no cap at all. Adds limit and offset to both, defaulting to 100 and clamping at 1000 rather than erroring, so an over-eager caller still gets a usable answer. The response now carries total, returned, offset, and limit, so a consumer can tell a complete answer from the first page of a long one and knows how to ask for the rest. Verified live against Cook County: the default call drops from 351,820 to 40,550 characters, and offset=800&limit=3 returns the expected tail of the 808 matches. Tool descriptions now state the paging behaviour and that table_name is only non-null when synced is true, since a description is the only documentation an agent reads. Closes P2-2 from docs/qa-report-2026-08-06.md. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Both High-severity defects are now closed, 4 of 7 overall. Adds Resolution sections for P1-2 (95d56b3) and P2-2 (c7def9c) with the live verification figures, and notes that P1-2 was present in describe_dataset too — where it drove a lookup against a table that never existed — not only in list_datasets as originally filed. The substantive addition is Rev 4's observation that the three fixed defects each represent a different testing failure, with a different remedy. P2-1 was fixture drift: the test held a wrong belief about the API. P1-2 was a wrong requirement written into an assertion: the suite asserted the synthesised table_name was correct, so running it more often would never have helped. P1-1 was an untested cross-process property. No single practice catches all three, which is a more useful conclusion than any individual finding here. Executive summary rewritten to lead with that rather than with the defect list. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
corruption and police hardcoded portal: data.cityofchicago.org and a
list of Chicago 4x4 ids. They were Chicago modes wearing generic names —
supporting a second city meant editing the mode, so in practice it never
happens and "police monitoring" means "Chicago police monitoring"
forever.
A mode now declares Concepts: logical tables described by what they must
contain ("contracts with a vendor, department, and award amount") rather
than which dataset supplies them. A Binding maps one portal's datasets
onto those concepts. Queries reference {{c:name}} and are resolved
against the binding at run time. Adding a city is a new Binding; the
mode is untouched.
bindings_chicago.go is the reference binding and the template to copy.
Every id and row count in it was verified against the live API.
Partial bindings are first-class. A portal that publishes complaints but
no per-officer breakdown binds what it has; Runnable reports which
concepts a query needs, and modes run skips those queries naming the
missing concepts rather than failing with a binder error. This matters
because cities differ enormously here — some publish officer
identifiers, some do not — and approximating across that gap would
produce confident nonsense.
Bindings also carry Notes, which is where portal-specific truth lives:
Chicago's COPA extracts have no officer identifier, and Chicago's
lobbying counts are high because its disclosure regime is strict, not
because there is more lobbying. Both are now attached to the binding
rather than buried in a mode comment, so a second city's differences
land in the same place.
Mode caveats were rewritten to be portal-neutral, and two comparability
caveats added — complaint volume and lobbying counts must never be used
to rank cities, since both track disclosure rules rather than conduct.
CLI: modes show lists concepts and every bound portal with its notes;
modes init takes --portal and defaults to the sole binding; modes run
derives the portal from the filename (csq does not record it in the
file) with a --portal override.
ranking and research are unaffected — they read only the _csq schema and
were already portal-agnostic.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Adding a city required editing Go and rebuilding csq, which in practice
means it is done by whoever maintains the repo and nobody else. Modes
and bindings are now loadable from ~/.csq/modes/*.yaml — override with
--modes-dir or CSQ_MODES_DIR — so a city, or a whole analysis profile,
can be contributed as a config file.
A file declares kind: mode or kind: binding. Loading is two-pass so a
binding may reference a mode defined in a file that sorts later;
directory order is not something an author should have to think about.
An external mode replaces a built-in of the same name, so a shipped mode
can be corrected or extended without a rebuild.
Validation is strict and written for someone who is not a Go programmer.
KnownFields(true) means a typo like `citty:` fails naming the key rather
than being silently dropped — the failure mode that would otherwise have
someone wondering why their city label never appears. Errors name the
file, the field, and the fix.
Three rules are enforced rather than documented:
- a mode without caveats is rejected, matching what the built-in
registry test already requires, because these profiles report on
procurement and policing
- a query must reference {{c:name}}, so an author cannot hardcode a
table and quietly make their mode single-city
- a binding may only map concepts its mode declares, listing the valid
names when it does not
New subcommands: `csq modes lint <file>` checks a file before use, and
`csq modes where` reports the directory and what was loaded from it.
`modes show` now prints the source file for external modes and bindings
so a user can tell which file to edit.
A broken file warns and is skipped rather than being fatal: one bad
contribution should not make csq unusable.
Verified end to end with an external Seattle binding carrying only the
complaints concept — it loads alongside Chicago and reports the three
unbound concepts as "not published by this portal".
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
ranking compared dataset counts and sync freshness — open-data
transparency, not anything about living somewhere. Someone choosing a
city got "Chicago publishes 2,010 datasets, 99.1% documented", which is
not a livability answer with a caveat attached; there was no livability
data in the mode at all.
It now compares real indicators through the concept/binding layer:
reported offences, 311 responsiveness and load, and permit activity —
each normalised per resident. Every query is written for one city and
unioned across the attached cities with a leading city column.
Three rules are enforced in code, not documented, because the audience
includes people making a decision about where to live and they are the
least equipped to catch a bad number:
- No composite score. Separate indicators only. A test fails the build
if a query name or description starts to look like one. Any weighting
that produces a single number is an editorial judgement, and shipping
it as arithmetic would be dishonest.
- Absent data is never a good result. A city that cannot answer a query
is excluded by name with the reason ("does not publish crimes", "no
population recorded"), and a single qualifying city is labelled as not
a comparison. Silently dropping a city would make a portal that
publishes nothing look safe, which is the most consequential way this
could mislead someone.
- Raw counts are never compared across cities. Queries normalise via
{{POP}}, and expansion errors rather than dividing by a missing
population — a raw count ranking is a population ranking in disguise.
Population lives on the binding with a mandatory population_source; the
loader rejects one without the other. That sidesteps a Census ingestion
path for now while keeping the denominator citable.
Caveats state what the numbers cannot show, including that reported crime
measures reporting and recording rather than crime, that rates for
earlier years use today's population, that city boundaries are not metro
areas, and that this cannot tell anyone where to live — variation within
a city usually exceeds variation between cities.
Chicago's binding uses ijzp-q8t2, v6vf-nfxy, and ydr8-5enu, all verified
live with schemas and row counts. Its notes record the December 2018 311
consolidation and that its unusually granular crime publishing makes
naive cross-city rate comparison a comparison of publishing practice.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
…rtal
Adding a second city proved the concept layer was still Chicago-shaped.
Concepts declared canonical column names lifted straight from Chicago's
tables: an offence date was `date` and its category `primary_type`. NYPD
calls them `cmplnt_fr_dt` and `ofns_desc`, and DOB calls a permit date
`issuance_date` rather than `issue_date`. Nothing makes either set more
correct, so concepts keep canonical names and each binding declares its
own mapping.
BoundDataset gains Columns, and {{c:name}} now expands to a canonical
projection that renames the portal's columns rather than to the raw
table. Queries stay readable and portable; an omitted Columns map means
identity, so existing bindings are unaffected.
The more consequential half is what happens when a column does not
exist. NYPD's complaint extract records no arrest flag — arrests are
published separately with no join key. Emitting NULL would have shown
New York with an arrest share of 0%, indistinguishable from a city that
makes no arrests, which is precisely the failure this mode is built to
avoid. A non-empty Columns map is therefore authoritative: a concept
column absent from it is unavailable, and any query reading it excludes
the city by name with the reason. NYC is excluded from arrest-share and
compared normally on the other five indicators.
Column-use detection is word-boundary matched so `date` does not match
inside `created_date`; that has a test, because a false positive here
would silently drop a city from a comparison it could answer.
Both cities are now bound for crime rate, 311 responsiveness, 311 load,
and permit activity — the first real comparison this mode can make.
Every id, column, and row count in the NYC binding was verified live.
Its notes record the things that make a naive comparison wrong: NY penal
law categories do not map onto Chicago's IUCR, the 311 extract starts in
2020, and DOB counts renewals as separate rows.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Generated by `csq modes init ranking --portal <host>` from the two ranking bindings, covering the three indicator datasets each city publishes: reported offences, 311 service requests, and building permits. ~23.9M rows for Chicago, ~36.2M for New York. Committed while both syncs are still running. Every dataset id resolves and every table override is producing rows, which is what these files assert; final row counts are verified separately against upstream count(*) once the syncs finish. The two files are not interchangeable despite covering the same indicators — the table names differ because the bindings map each portal's columns onto the concepts, and the underlying datasets carry genuinely different shapes. NYPD's complaint extract has no arrest flag, so New York is excluded from arrest-share by name rather than reported as zero. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
A connection reset part-way through a response body arrived as a decode
error, not a network error, so the client gave up on what was squarely a
blip: the status line had already said 200. Both ranking syncs died this
way on 2026-08-14 ("decode page: read tcp ...: operation timed out"),
discarding every row read up to that point.
The body is now read to completion inside the retry loop, so a truncated
read is retryable; a JSON error on a body that arrived intact is not,
since asking again produces the same bytes. Adds full jitter so
concurrent workers don't resynchronise into a burst after a portal
hiccup, honours Retry-After, raises the default retry budget 5 -> 8 with
a 30s ceiling, and threads context through the backoff so Ctrl-C during
a wait no longer feels like a hang.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHsRquLojkKCkMjCzkJcP5
SwapIn drops the staging table it consumes, so a run that dies mid-stream leaves its partial table behind with nothing to reclaim it: each run stages under its own <table>_<runID> name, so the next run never reuses it and it survives until the schema is dropped. This is not hypothetical. The six ranking syncs that failed on 2026-08-14 left 945,000 unreachable rows across the Chicago and New York databases -- 315MB of files whose main schema is empty. Errors are ignored at the call sites: this runs on the failure path, where the error that got us there is the one worth reporting. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HHsRquLojkKCkMjCzkJcP5
DOB Permit Issuance publishes issuance_date as a text column holding MM/DD/YYYY, not a date. The binding mapped it as a plain column, so permit-activity did not return odd numbers -- it could not run at all: DuckDB refuses to compare VARCHAR '06/17/2020' against a DATE, and date_part has no candidate overload for one. A binding value may now be any SQL expression over the portal's columns, which CanonicalView already emitted verbatim; this documents that and uses it. try_strptime rather than strptime because the column carries unparseable values that would otherwise abort the query. Worth noting for anyone filtering this dataset upstream: a SoQL range predicate on the raw column compares lexicographically, so `issuance_date >= '2015-01-01'` matches 8,204 of 3,989,937 rows while looking like a valid result. Found by running the mode against live portal data; every existing test passed with the broken mapping, since a valid column name is all they could check. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01HHsRquLojkKCkMjCzkJcP5
The CLI runner expanded a query, executed it, and printed it in one pass, with the exclusion reporting written straight to stdout. That is fine for a terminal and unusable for anything else: a second interface needs the decisions -- which cities can answer, which were excluded and why, whether one qualifying city still counts as a comparison -- as data. Rebuilding that reasoning behind a second interface would be the surest way to have the two disagree, and the parts most likely to drift are exactly the ones that keep absent data from reading as a good result. So the decisions move here and interfaces only render them. Exclusion is a first-class result field rather than a log line, so no consumer can show rows without also receiving the reasons a city is missing from them. Readiness is the other half. "This analysis has no data yet" and "this analysis found nothing" look identical in a table and mean opposite things, so ModeStatus separates three states that the CLI conflated: not applicable (no binding for this portal -- a property of the city, and no amount of syncing fixes it), applicable but unsynced (carries the command that fixes it), and ready. Row counts come from duckdb_tables()'s estimated_size, which is exact for a table with no pending changes -- the case by construction, since every database is attached read-only. Refresh exists because a READ_ONLY attach is a snapshot bound at ATTACH time. Measured: one process can hold a file read-write while an in-memory host has it attached read-only, and both work -- but the attached view never sees the writes. Detach and re-attach picks them up. Without this a sync would succeed and the reader would go on reporting no data. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8
A terminal is a barrier for people who have every other qualification to read this data. The analyses csq ships are aimed at reporters, researchers, and residents, and requiring them to know what a --db flag is filters that audience by the wrong criterion. `csq web` serves the same modes as a local page, embedded in the binary via go:embed -- no install step, no node toolchain, no files next to the executable. Three views: Analyses (mode cards with a readiness dot), Explore data (every dataset the portal publishes and whether you hold a copy), and Data health (the research mode in plain language). Two properties are structural rather than incidental. The browser cannot send SQL. Every endpoint takes a mode name and a query name and runs the SQL the mode declares. That removes the injection surface a local SQL console would open, and means what runs in the page is exactly what `csq modes run` runs, caveats included. Caveats and exclusions ship in the same payload as the rows, and the page has no code path that renders a table without them. An excluded city is named above the numbers rather than in a footnote below them, because a reader who sees the table first has already drawn a conclusion. Charting is deliberately narrow, and the decision is made server-side so the page and the exported report cannot disagree about the same numbers. A chart needs one text column to name the bars and a measure to size them; results with several numeric columns of different units stay tables, because the chart that would fit them is a dual-axis chart. The measure is the column the query sorted by, not the first numeric one -- top-vendors returns (vendor, contracts, total_awarded, avg_award) ordered by value, and charting the count would draw bars in visibly jumbled order beside a correctly sorted table. Series cap at two cities: past that, generating a third hue is the documented wrong answer, so the chart is dropped and the table carries the result. With --config the page can also download the datasets an analysis needs. Those downloads take the same advisory lock csq sync takes, and one runs at a time -- DuckDB permits many readers or one writer, so a second concurrent download would surface as a lock error partway through a long transfer rather than as a refusal at the start. Progress streams over SSE. Shutdown cancels a running download rather than letting the process die mid-write, which would strand a staging table nothing reclaims. The writer is closed before the post-sync re-attach, and not on a defer: a READ_ONLY attach replays the write-ahead log into the database file and cannot while the read-write handle still holds it. Found by running a real 235,860-row download, which failed with "Bad file descriptor" after every dataset had synced successfully. `csq web --db new.duckdb --config portal.yaml` creates the database if it is missing. Someone opening this for the first time has no database -- getting one is what they came for, and refusing to start until they had already run a sync from a terminal would put the barrier back exactly where this is meant to remove it. The default address is loopback and the server says so; csq has no login, so a wider --addr publishes every synced dataset to anyone who can reach the port, and that warns. Also corrects the ranking one-liner in the top-level usage, which still described the pre-28baa35 mode. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8
Covers the three views, the two structural properties (the browser cannot author SQL; caveats and exclusions travel with the rows), the --config gate for downloading, the standalone HTML report, and the loopback default with the reason it is the default. Also notes the browser entry point in the status line, since the quickstart otherwise opens with a go build and three flags. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8
Three gaps that kept the page from being usable on its own. Tables sort by any column and filter as you type. Both operate on the rows already in the browser and never re-run the query: that keeps them instant, and it keeps the guarantee that the page cannot author SQL -- rearranging rows you were already given is not the same as asking a new question. The caption states how many rows the view shows out of how many were returned, because a filtered table that does not say it is filtered is a misleading object. Sorting copies before it sorts; res.rows is also what the chart reads, and reordering it underneath would make the two disagree. Exports re-run the query server-side with a far higher row cap than the page displays, so what downloads is the whole result rather than the 1000-row view. Both formats carry the caveats and the excluded cities -- CSV as comment rows above the header, JSON as fields. An export that dropped them turns a hedged answer into a bare spreadsheet, which is how these numbers get misquoted. The comment rows are padded to the column width: a file whose rows have differing field counts is not valid CSV, and strict parsers reject the whole file rather than the offending line, which would lose the data as the price of carrying the warnings. Floats are written in decimal notation because fmt.Sprint renders a large one as 1.24864646192e+10, which several spreadsheet imports mangle. The city picker is the bigger change. Everything else in csq assumed you already had a database, and getting the first one meant knowing that `csq modes init` writes a YAML that `csq sync` then consumes -- three pieces of vocabulary before a single number appears. `csq web` with no --db now opens on a list of cities csq has bindings for; pick one, pick an analysis, see how many datasets and roughly how long, confirm. It states the cost before committing to it, because a download measured in tens of minutes should not begin because someone clicked a card. Setup writes the config to disk rather than holding it in memory, so what you set up in the page stays drivable from the command line; a UI that creates state its own CLI cannot see is a trap. The portal is resolved through the binding registry rather than trusted, so a request cannot name an arbitrary host and have files created for it, and the filenames derive from csq's registry rather than from user input. --db turns setup off: naming your own databases is a statement that you did not ask csq to invent more. Supporting changes: Session now accepts zero portals and gains Attach, since the setup flow adds a portal while the server is serving. The portal slice is no longer fixed at construction, so it moves behind an RWMutex and every read takes a snapshot. The event stream is opened only while a download is running and closed when it reaches a terminal state. An always-open EventSource holds a connection for something that is not happening, costs a goroutine and a subscriber slot per open tab, and keeps the page permanently "loading" to anything measuring network idle -- which is also what made it impossible to screenshot. showViewChrome splits the tab toggle from the render dispatch. The setup flow lives inside the analyses tab, and having it call switchView made the two call each other until the stack ran out. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8
It still read Phase 4 while phases 5, 6, and 7 have all shipped, so the first thing anyone reads about this project understated it by three phases. Salvaged from ca8b832, which bundled this correction with a livability index design that does not belong on this branch. The design document and its README section were dropped; they are preserved on the livability-design branch. Only the status paragraph is kept here, verbatim as that commit wrote it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8
$offset makes the portal scan and discard every row before the offset, so
page cost grows with depth and total sync cost grows quadratically. This
is not a tuning problem. Measured today against live portals:
Chicago crimes, one 5,000-row page
offset 0 5.0s
offset 1,000,000 8.4s
offset 2,500,000 36.3s
keyset, same depth 4.4s
NYC nypd_complaints
offset 3,000,000 13.7s
offset 3,135,000 no response in 200s
The NYC sync did not finish and could not have: past roughly 3.1M rows the
portal stopped answering, and csq sat on an established socket waiting.
Seeking with ":id > '<last>'" keeps every page at the offset-0 cost
regardless of depth.
Applies only when the stream is ordered by :id and :id is in the
projection, which is csq's default. Anything else keeps $offset, as does a
row whose :id does not match the expected shape -- an unrecognised key
falls back rather than being interpolated into a predicate.
The fake portal now models seeks too. Without that it would serve page one
for ever, and FailAtOffset -- which several paging tests depend on -- would
never fire.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HHsRquLojkKCkMjCzkJcP5
The strategies drop their own staging table when a sync returns an error, which covers a sync that fails. Nothing runs when the process is killed instead -- and then the staging table survives forever, because each run stages under a fresh run ID so no later run ever reuses or reclaims it. The run row is left at status 'running' with no finished_at, so the corpus reports a sync in flight that no longer exists. Measured on the two ranking databases after their syncs were killed mid-flight: 4,595,000 orphaned rows in Chicago against 3,372,967 live ones, and 3,580,000 in New York against 3,990,129. More dead weight than data in one of them, and the Chicago file shrank from 1.5G to 936M once swept. sync.Run now sweeps before it writes anything. Two properties make that safe, and both are load-bearing: Every path into Run holds the portal's advisory write lock -- the CLI, the MCP write tool, and the web server all acquire it first. With it held, no other csq process can be mid-sync against the file, so every staging table present belongs to a run that is over and every unfinished run row is abandoned rather than in progress. This was demonstrated accidentally while cleaning the real databases: New York refused the sweep because another process had restarted its sync, which is exactly the intended behaviour. Sweeping happens before any dataset starts, so the current run cannot have staging tables yet. That makes "everything in _csq_staging" and "everything from a previous run" the same set, and the simpler rule has no edge case where a stale table survives because its run ID looked current. A dry run sweeps nothing: it inspects, and deleting another run's working state is not inspection. The existing IncompleteSyncRunCount warning is kept and reworded. It fires before the sweep, because afterwards the count is zero and the fact that a previous sync died would vanish silently -- the point is to say it happened, not only to fix it. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8
… the query A concept can be bound and its table never synced. Comparable only reads the binding, which describes what the portal publishes -- not what you hold -- so it passed, and the query then died on a DuckDB binder error naming the missing table. In a cross-city union that took every other city's answer down with it: 311-load returned nothing at all because New York had not synced its service requests, even though Chicago's 14.5M rows were sitting right there. ComparableWith adds the presence check, and both planners use it -- the CLI and the web server -- so the two cannot disagree about which cities are in a comparison. The two exclusion reasons are kept distinct because their remedies are: New York, NY (does not record arrest) New York, NY (has not synced service_requests yet) The first will never change; the second is one command away. Collapsing them into "no data" would tell someone to stop looking when they should sync, or to sync when the city simply does not publish it. An inspection failure yields a nil lookup, which is treated as "do not exclude" rather than "absent". A problem reading the local catalog must not masquerade as missing data and silently drop a city from a comparison -- that is the failure this mode exists to prevent, arriving by a different door. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8
fix(cli): print floats in decimal, not scientific notation
A mode hands you a table. `csq investigate "<question>"` returns a verdict, a confidence, the findings behind it, and the reasons it might be wrong — which is a much stronger claim to make, so most of this is machinery for not making it carelessly. Seven steps, in an order that is load-bearing rather than decorative. Plan runs before Analyze so the indicators, and the direction of each that would count as evidence, are fixed before anyone has seen a number; an investigation that picks its indicators after seeing the results is an argument. Validate runs before Analyze so a series is never measured past where its data stops. Challenge runs after, because the attack is the only thing between "records fell 12%" and "the year is not over yet". Three refusals shape the design: It does not write SQL from the question. Probes are declared in the registry, reviewed like any other code, and expanded through the same concept bindings the modes use — so an investigation is portable across cities for the same reason a mode is. A question nothing covers is refused rather than improvised, and two investigations matching equally well is a question to the user, not a coin toss: guessing yields a confident, fully caveated verdict about the wrong question. It does not weigh findings. A challenge withdraws a finding or annotates it; neither applies a numeric penalty, because scoring one down by some fraction needs a coefficient nobody can derive. The verdict counts what survived. It does not invent a confidence number. It is the confidence package's R multiplied by the share of planned indicators that produced a measurement — both counts over counts, so the product keeps a plain reading and adds no constant. Coverage counts findings rather than runnable probes: a probe whose tables are present can still return a series too short to compare, and crediting that would flatter the score. Two probe fields exist because their absence produced a specific wrong answer against Chicago's real COPA caseload. `SettlesAfter` holds back periods where the field being read has not finished filling in — without it, "what share of cases carry an outcome" reports the age of the caseload as a disclosure failure. `MeasuresAbsenceOf` excludes from the evidence profile the columns whose emptiness *is* the observation: 73% of Chicago's cases lack a finding_code, and scoring those as missing evidence made an indicator that read every record it needed report 7% confidence. Coverage is measured at both ends. A dataset beginning in July holds half a first year, and half a year read as a year makes the following year look like a surge — the mirror of the part-finished last year looking like a collapse. Chicago's 311 record starting December 2018 is exactly this. Two investigations ship: police-transparency over the police mode, and civic-publishing over ranking, which exercises a different mode, different concepts and a different binding with every step unchanged. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01L5AbMyrdcNP6cyJvaE3cAD
feat(investigate): answer a civic question, and show the working
Review of the formula turned up one latent defect and one inaccurate claim. The defect: TargetsFor built one target per concept, so two concepts satisfied by the same dataset produced two identical targets. R is the product of per-target retentions, so that table's retention would be squared — a dataset holding 60% of its evidence scoring 36%, a loss counted once in the data and twice in the arithmetic. No binding does this today, which is why nothing caught it, but a binding is a config change and the failure would be silent. Targets naming the same dataset now merge, taking the union of their columns, which is what the joint usability filter needs anyway. The claim: the docs say R reads as "the share of the records the query meant to consult that were actually there and usable". That is exact for one dataset, where R is U/E. Across datasets R is their product, which answers a different question — every dataset held up, rather than this share of the pooled records held up. Two datasets each retaining half give 25%, while half the pooled records survived. The conjunctive reading is exact for a join and a lower bound for a union, so it is the conservative choice and worth keeping; it just needed saying. Both the package doc and the README now distinguish the two, and a test pins the distinction so a later change has to be deliberate. Worth noting the product across datasets makes the same independence assumption the package rejects one level down, where it insists on measuring U with one joint filter rather than multiplying per-column rates. Measuring across datasets jointly is not possible without executing the query's own join, so the bound stands — documented rather than hidden. No score moves: all six Chicago corruption queries read one dataset each and still report 100, 94, 30, 100, 100 and 100. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01CGS7TRnt9Ms87ELnsGcZAB
fix(confidence): profile a dataset once, and state R's reach honestly
Modes were already data, but only YAML data, and writing one still meant knowing the format by reading the built-ins. This adds the two halves that let someone produce a mode without either: a JSON path into the loader, and a mode that drafts itself from a question. The loader now reads .json alongside .yaml — same fields, same validator, same strict rejection of unknown keys, since a silently dropped `caveats` or `columns` yields a mode that runs and answers wrongly. Two fields the external format was missing are carried through: `entity`/`measure`, without which a hand-written mode silently loses its concentration reading, and `columns`, without which an external binding cannot express the SQL mapping that lets a portal publishing money as text bind at all. `schema.go` is the single copy of the document's JSON Schema: `csq modes schema` prints it and the personal mode constrains the model to it, so the grammar a person writes and the grammar a model emits cannot drift apart. `csq modes personal "<question>" --db <file>` shows Claude the schema of the tables you hold and asks for concepts, SQL, and caveats. The model authors a mode; it never answers the question. Four gates stand between a draft and the disk: a read-only SQL guard, a cross-check that every bound table and column exists locally, the loader's own validation, and EXPLAIN on every new query — the last being the only one that can prove the SQL resolves against the columns it claims to read. Any failure rolls both files back. What lands is an ordinary mode file the user owns: same runner, same bindings, same confidence arithmetic. Asking again appends, and the merge is deterministic with the existing file winning every conflict, so an edited caveat or a corrected column mapping survives the next question. The built-in `personal` ships empty — an inventory of what you hold — and is replaced by the drafted file via the loader's existing same-name override. It declares no concepts on purpose: a concept-based mode with no binding cannot run, and modes_test.go fails the build for one. Scope limits, stated where they are load-bearing: no rows leave the machine unless --samples is passed, the network call is confirmed before it is made, and every drafted mode carries a non-removable caveat that a model chose its columns and can misread what one means. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
Everything else in the package proves the machinery around a draft; nothing proved that a real reply survives it. This runs the whole path with the model in it — inventory, draft, guard, save, plan, execute — and asserts the parts that must hold for any draft: a non-empty query set, the non-removable provenance caveat, a dropped population, files the loader accepts, queries DuckDB can plan, and a first query that actually returns rows. It deliberately does not assert wording. A model may reasonably name a query anything, and a test pinning the prose would fail on a better draft. Gated twice — CSQ_LIVE_API=1 and working credentials — because a test that silently bills whoever runs `go test ./...` is a bug. CI sets neither, so it skips there. CSQ_LIVE_DB points it at a real portal database, which is where the prompt is judged rather than the plumbing. The no-credentials path is asserted in the ordinary suite, since it makes no call: csq must fail with guidance naming both ways to supply a credential, not with a bare API error. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
Drafting is the only billed step in csq, and asking the same question twice paid for it twice. This caches the model's reply — and only the reply. What is cached and what is not is the design. A draft is code: given the same question, schema, prompt and model, the SQL means the same thing tomorrow. A query result is data the portal may since have revised, and reusing one would put a stale figure on screen behind a confidence score that says otherwise. So `csq modes run` still re-executes against DuckDB, every time. An entry is reused only when every input still matches: question, model, effort, csq's authoring instructions, the mode-file schema, the tables held (columns, types, and sampled values), and the mode already on disk. The fingerprint is built next to the prompt it fingerprints, because adding an input to one and forgetting the other is how a cache starts serving SQL written for a schema that no longer exists. Two properties fall out of storing the raw reply rather than a checked draft. A hit skips the network call and nothing else — guard, cross-check, loader validation and EXPLAIN all still run, so a cached draft is never trusted more than a fresh one. And since a hit makes no call, it needs no credential and no confirmation: the CLI peeks before it asks permission to contact anything, because asking to contact a service it is not about to contact would train the user to dismiss the prompt that matters. Miss, stale and corrupt are distinct states carrying distinct reasons, on the same principle that keeps "could not measure" apart from "measured zero" elsewhere. Staleness is normal and names what changed; corruption means an entry is damaged or misdescribes itself, which is what `csq cache verify` exists to find. No expiry on read — the fingerprint, not the clock, decides whether a draft still applies. Found while testing: json.MarshalIndent re-indents an embedded json.RawMessage, so a payload stored that way never round-trips byte-exactly and its checksum failed on every single read. The payload is a string now. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
The personal mode had one authoring path and it needed a credential. This
adds the offline one, and makes it the default suggestion.
Most civic analysis is a handful of shapes. "Which vendors got the most
money", "which contractors pull the most permits", "who receives the most
contributions" are one shape — rank entities by a summed measure — pointed at
different columns. Six such shapes ship here as reviewed SQL templates with
holes for the columns the user names: top-n, concentration, trend, breakdown,
coverage, and name-variants.
The output is the same pair of documents `csq modes personal` drafts, through
the same loader, the same read-only guard, and the same EXPLAIN check.
Nothing downstream can tell them apart, which was always the point — the model
was one way to write the file, not the system.
Patterns beat drafting on more than cost. The caveats that matter most are
properties of the shape, not the data: a top-N always hides its tail, a
free-text entity column always understates concentration because one body
appears under several spellings, a count by month is always distorted by a
partial final month. Written once against the pattern and reviewed, they are
correct on every use rather than regenerated each time.
Two things the builder gets right that are easy to miss by hand, both decided
from the declared type and never from a column's name:
- a VARCHAR measure is wrapped in TRY_CAST, so one unparseable row becomes a
NULL the confidence score counts rather than a query that dies or, worse,
silently coerces;
- a text date is refused unless --date-format says how to read it, because
guessing between MM/DD/YYYY and DD/MM/YYYY mislabels a third of the year
without ever raising an error.
Also fixes two merge bugs that predate this and would have bitten the drafted
path too. A second query against a known table commonly needs one more column
from it; concepts and binding column maps now merge column-wise instead of
being skipped wholesale, so that column is declared and mapped rather than
left dangling. Since a non-empty columns map is authoritative, the old
behaviour made the column read as unavailable rather than as merely unmapped.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
`csq modes ask "which vendors got the most money?" --db chicago.duckdb`
now works with no credential, no network, and no model — it matches the
question against the six analysis patterns and the columns of the tables you
actually hold, shows what it picked and why, and builds the mode on confirm.
This is viable only because the answer space is small. csq is not translating
a question into arbitrary SQL, which is the brittle version and the one whose
failure mode is a plausible-looking wrong query. It ranks six reviewed shapes
against the columns of one table — a few dozen candidates — which keyword
scoring over the user's own schema handles honestly.
Three rules keep it from becoming the brittle version. It shows the word
behind every choice, so a wrong guess is visible before anything is saved. It
refuses rather than guesses: an unplaceable question, or a role with no
plausible column, comes back as a message naming the explicit `csq modes add`
command instead, and a question asking for the *least* is warned that the
shape ranks largest-first. And it never writes SQL — the worst it can do is
pick the wrong template, which a person still wrote and reviewed.
Column scoring weighs the declared type as hard evidence and the name as soft,
since a scorer that ignored types would happily sum a telephone number. Roles
are filled greedily with no column reused: one column serving as both the
group and the entity yields a share that is always 100%.
Two bugs found by testing against a two-table portal, both now covered:
- concentration came out with group and entity swapped, because "name" sat
in the synonym expansion for "vendor" and inflated every *_name column.
Role vocabulary now outweighs question-word matches, and "name" is gone
from the synonyms — it is too generic to be a synonym for anything.
- a long column name shoved the reasoning column out of alignment, which
matters because the reasoning is the part meant to be read.
`ask` and `add` share one build-and-save path, so the two commands cannot
produce different files for the same choices.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
…s columns Testing `csq modes ask` against Chicago's real tables — 14.5M 311 requests, 2.9M crimes, 470k building permits — turned up two cases where it produced a query that ran cleanly and reported a number that meant nothing. That is worse than refusing, so both are fixed and pinned. The 311 table has exactly one numeric column: community_area, a geographic identifier. Asked how requests were trending, the router filled the trend pattern's *optional* measure with it and summed area codes by month. An optional role was being filled on type evidence alone. The crimes table has fbi_code, a classification held as text. Asked for a breakdown by primary type, "type" reached fbi_code through the category synonyms, qualifying it as a measure; the result summed classification codes into totals that look entirely real. So name evidence is no longer sufficient either — an optional role is now filled only when the column matches that role's *own* vocabulary. Question words can rank candidates; they cannot qualify one for a role it does not look like. Also: building_permits carries a dozen fee columns, and "which permit types collect the most fees" picked building_fee_paid over total_fee purely on declaration order. Among candidates matching equally well the router now prefers the least qualified name, which is what a person means by "the fees". Each of the three has a regression test built from the real schema that produced it. What the run confirmed working, on real data: 98 months of 311 volume, $224M of permit fees by type with the 45.3% concentration flagged, crime breakdown, column coverage (permit_condition is 3.5% populated), and name-variants finding PARTYTIME HDO under 10 spellings across 219 records, T-MOBILE under 5 across 472, and CITY OF CHICAGO under 4 across 630 — real duplication that would split a contractor ranking ten ways. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
…olumns
Probing the router with 22 realistic phrasings against Chicago's real tables
found 6 wrong routings and 5 unhelpful refusals. It now routes 18 of the 22
correctly and refuses the other 4 for reasons it can state.
The largest gap was that "the most" has two ordinary readings and only one was
supported. "Which contractors pulled the most permits" is a count; "who was
paid the most" is a sum. top-n required a measure, so counting questions
forced it to reach for any numeric column — crimes.id, requests_311.ward —
and rank by a meaningless sum. The measure is now optional: given one, rows
are summed; without one, they are counted, and the record count stays in the
output either way because one contract worth $10M and a thousand worth $10M
each are different findings. A measure is attached only when the wording
actually reaches for a quantity, which is the only thing that can distinguish
the two readings.
Five narrower fixes, each from a question that failed:
- Vocabulary phrases containing a stopword never matched at all. Bigrams
were built after stopwords were dropped, so "by month", "by year" and
"what kind" could not form; "show me permits by month" and "arrests by
year" were refused outright. Bigrams are now built before filtering.
- A word the user typed now outranks one reached through the synonym table,
which outranks the generic role vocabulary. "Which wards have the most 311
requests" was landing on `precinct`, a synonym of ward, over `ward`.
- A column named after its own table is that table's identifier, not a
description: building_permits.permit_ was winning the entity role.
- Timestamps and booleans are no longer eligible as entities or categories.
Ranking 2.9M distinct timestamps answers nothing, and crimes.arrest splits
everything into two rows.
- A table the question is plainly about is no longer silently swapped for
another when it cannot answer. "Is any crime type concentrated in one
district" was coming back about building permits — correctly labelled and
entirely beside the point — because crimes has no measure-shaped column.
That now refuses and says which column is missing.
Everything above has a regression test built from the schema that produced it.
Confirmed on real data: ADT,LLC leads with 8,954 permits pulled, a ranking the
old code could not express.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
The draft cache landed earlier this session with JSON entries, a fingerprint over every input, and verdicts that distinguish miss from stale from corrupt. Two things it did not have were the two the request names: a bound on how much it can hold, and any measurement of what it saves. Memory. The store was unbounded — Prune took an age and nothing else, so nothing capped entry count or bytes and nothing evicted on write. It now holds at most 200 entries or 32 MB (CSQ_CACHE_MAX_ENTRIES, CSQ_CACHE_MAX_BYTES; 0 removes a ceiling) and enforces that from Put rather than on a schedule. A cache that only shrinks when someone remembers to prune it grows without limit in practice, and a write is exactly when its size is known to have changed. Eviction is least-recently-*used*, not oldest-written. The entry someone keeps coming back to is the one whose re-drafting would cost most, so a draft written months ago and used yesterday outranks one written yesterday and never used again. `cache prune` gains --max-entries and --max-bytes for reclaiming space now without changing what every future run enforces. Tokens. Entries now record the input and output tokens of the call that produced them, carried back from the API response through llm.Result. Stats reports two figures: what it cost to produce what is held, and what reuse avoided re-paying. Entries written before this existed contribute zero, which understates the saving rather than inventing one — the same reason an unassessed confidence score renders as "not assessed" rather than 0%. Worth stating plainly: this only ever mattered for the drafted path. The pattern router makes no API calls at all, so on the keyless path there is nothing to cache and nothing to save. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
csq no longer talks to any model. `csq modes personal` and `csq cache` are gone, along with internal/llm, internal/cache, and the Anthropic SDK dependency. What remains is the path that needed no credential anyway: `csq modes ask` matches a question against reviewed SQL patterns and the columns of the tables you hold, and `csq modes add` drives a pattern directly. Deleted outright: the Anthropic client, the draft cache with its fingerprint and eviction, the drafting command, the live API test, and the Author/Peek/ Fingerprint half of internal/personal along with the prompt that fed them. Kept, because the pattern path was already built on them: the schema inventory (Describe, SampleColumns), the read-only SQL guard, the mode documents and their merge rules, and the save-load-EXPLAIN-rollback path. Those moved to document.go so what survives reads as a unit rather than as the residue of a larger file. Portal.Shape went with the cache — it existed only to feed a fingerprint. Two things worth noting about what this does *not* change. The JSON mode format, its schema, and the strict loader stay exactly as they were: they were never specific to the drafted path, and `csq modes schema` remains the single description of what a mode file may contain. And the guard, the loader validation and the EXPLAIN check still run on every generated query — they were never there because a model wrote the SQL, but because SQL nobody reviewed is about to execute. Prose throughout has been rewritten rather than patched. "No API key required" was a selling point when there was an alternative; with nothing to contrast against it says nothing, so the docs now state what the router does instead of what it avoids. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
`csq modes show <mode>` listed every query's name and description and then stopped, so the SQL — the part that says what a number actually measures — appeared nowhere. Reported as corruption.go looking blank after its queries; the file was fine, the command was hiding what it holds. This was worse than an omission. Several caveats csq attaches to its own results say to read the SQL under `csq modes show` before quoting a figure, and `csq modes patterns show` has always printed the SQL behind a pattern. So the tool gave an instruction its own command could not satisfy, on exactly the point where checking matters most. Queries declaring an entity and a measure now also state the concentration reading they produce, since that is the other thing about a query that changes how its output should be read. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
Everything the router knew came from Chicago. Running it against NYPD's
complaint extract and Cook County's court data — 5.4M and 3.1M rows, naming
conventions it had never seen — found six failures, three of them caused by
Chicago-shaped rules that were wrong in general.
NYPD names columns ofns_desc, boro_nm, addr_pct_cd, cmplnt_fr_dt. None of that
is reachable from English, so questions about offenses, boroughs and precincts
all missed and settled for whatever else looked plausible: "how do complaints
break down by borough" grouped by the suspect's age group. Column names now
expand a small table of unambiguous civic contractions.
Three defects were self-inflicted:
- "offenses" ends in "ses", and the pluraliser treated it like "classes",
producing "offens" — a token matching nothing. That alone made ofns_desc
permanently unreachable. The rule now keys on "sses", so classes→class and
addresses→address still work while offenses→offense does too.
- A synonym mapping "complaint" to "type" had been added so Chicago's sr_type
would win one question. On NYPD it beat a word the user had actually typed.
Removed; sr→service reaches sr_type honestly instead.
- Expanding "tm" to "time" made cmplnt_to_tm — a time of day — outrank the
real timestamp for "trended over time", since the question contains "time".
Three rules that were missing rather than wrong:
- A word that selected the *pattern* is not evidence about the *table*.
"Which courts handle the most cases" picked Cook County's `initiation`
because its description contains "most", over the two tables that actually
have a court_name column.
- A word that identified the table has done its job and must not also pick a
column inside it, or "complaints" reaches cmplnt_to_tm on the very table it
just named.
- Identifiers are never a grouping. `case_id` won "which courts handle the
most cases", which answers with 1.2M rows of 1. Columns ending _id, _num,
_number or _key are now excluded from entity, category and group roles,
and ignored when judging what a table is about.
Table choice now scores how much of the question a table's columns *cover*
rather than its single best match, so a table with both a court and a case
column outranks one with only cases.
Chicago's results are unchanged, and the two questions that still miss now
refuse on an honest tie rather than answering about the wrong table.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
loader.go and schema.go still described JSON as the format "the personal mode writes a profile an LLM authored" and the schema as what constrains an "LLM-authored mode". Neither has been true since the API-key path was removed; both files now name the commands that actually write those documents. The similar wording left in document.go and ask.go is deliberate: one explains why the Draft type carries that name, the other states what the router is not. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01KBDemxnqukEq2ci2mYUohP
A generated binding recorded `rows` from duckdb_tables().estimated_size
— the size of the table already on disk. That field is the reference
count completeness is measured against, so E was set to H and
completeness became the ratio of the local copy to itself: a permanent
✓ 100% of expected rows present
which would read exactly the same after a sync that truncated half the
data. A check that cannot fail is worse than an absent one, because it
is displayed to the reader with a tick beside it. The hand-written
Chicago binding records 185,699, the verified upstream count, which is
why procurement-type can report 30% and a short sync shows up there.
The generator now omits the field. Confidence reports "expected row
count unknown — completeness not checked", excludes the factor from the
product, and lowers coverage to admit it. Anyone who knows the portal's
real count can put it in the binding by hand and get the check back.
Omitting it exposed a second display bug, not confined to generated
modes: any binding without a row count rendered as "~0 rows" in
`modes show`, `modes init`, and the web setup card, which reads as an
empty dataset promising an instant download. Unknown size now says so.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CGS7TRnt9Ms87ELnsGcZAB
fix(patterns): stop writing the local row count as the reference count
csq hands you its numbers as JSON — a mode result from the web UI's /export/<mode>/<query>.json, or the row objects from `csq query --format json` — and then leaves you to find something to plot them with. scripts/csq-graph.py turns either into a single self-contained HTML page: inline SVG, no dependencies, no network, no third-party JavaScript. The rules deciding whether a result may be drawn are the ones internal/web/chart.go already applies — one text column to name the marks, one numeric column to size them, a `city` column splitting them into series — so a chart made here and a chart made in the page are the same chart, including the refusals. A result that qualifies for none of them renders as a table with the reason printed above it, because a reader who sees no chart should not have to guess whether it is missing or was declined. Caveats, exclusions and the confidence report render above every figure, and there is no code path that draws one without them. Several numeric columns of different units become one measure plus a table rather than a dual-axis chart; past eight series it stays a table; a line chart whose axis starts above zero says so underneath. Every figure carries its own table view, which is both the accessibility fallback and where the full 184,320,991 stays reachable once the bar has been labelled 184.3M. Colours are the validated categorical palette in its documented order, slots 1 and 2 being the two the web UI's charts already use. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016KT2a8a4DoNFnpq1QFeEZx
Three things review caught in the figures themselves. The truncation note counted the wrong thing. A grouped chart draws one group from several rows, so "First 20 of 30 rows" appeared directly above a table view reporting 60 rows — two numbers describing the same result and disagreeing. It now names the unit it actually capped: "First 20 of 30 category values", and still says "rows" where one row is one bar. The stat tile dropped the series. A single-city figure that never says which city reads as a total across all of them, which is the failure the exclusions block exists to prevent — so the tile now names it. The tile also compacted four-digit numbers, rendering 1,200 as "1.2K" — no shorter, and less clear. Compacting starts at five digits. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016KT2a8a4DoNFnpq1QFeEZx
feat(scripts): chart exported JSON with no toolchain
`ranking` refuses to emit a composite score, and that refusal is right for what it compares. This records the design for the mode that would not have to refuse: make the weighting an input and then measure how much of the answer it drove. The load-bearing pieces are rank intervals over sampled weightings rather than a point rank, a dominance partial order reported separately as the claims that survive every weighting, affordability as a gate applied before scoring rather than a term added during it, and scoring each domain on its 10th-percentile neighbourhood as well as its median -- life expectancy varies by decades within Chicago alone, which is wider than the gap between most pairs of cities. Dataset ids in the criteria tables were verified against the live catalog API. The exercise surfaced two things worth recording: Chicago publishes no eviction dataset while NYC does, which the design handles by excluding Chicago from that indicator by name rather than scoring it zero; and roughly half of what makes a city livable is not on a Socrata portal at all, so an honest index needs a non-Socrata reference-data path. Nothing here is implemented, and the document says so at the top. Cherry-picked from ca8b832 on livability-design, which was the only commit on that branch not already present here. Its Status-line correction is dropped: 1ebd4c2 already moved the README to Phase 7. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Both of these came out of running the script against the real Chicago database rather than fixtures. nice_ticks could return a top tick below the maximum. The loop stopped half a step past the data, which sounds generous and is not: the ticks define the scale, so any value above the last one is drawn outside the plot instead of inside it. Chicago's crimes-by-year hit it exactly — a 250,000 top tick against a 269,997 maximum put 2015 through 2018 above the chart, and the line appeared to begin in 2019. Measured across 200,000 random ranges the old condition left the axis short of the data 48.6% of the time; the fixtures simply landed on the other half. Ticks now always span [min, max]. The label column stayed a measure candidate. It only shows when --label names a numeric column, which is the case the flag exists for: the ranking mode returns an integer `year`, and a sorted year column is indistinguishable from a sorted measure, so --label year charted year against itself and reported "Measure: year". The column naming the marks is now excluded from sizing them. Also corrected the from_records docstring, which claimed JSON record keys arrive in SELECT order. They do not: csq builds each record as a map[string]any and Go's encoder sorts map keys, so `SELECT sr_type, COUNT(*) AS requests` arrives requests-first. The order is gone before the JSON is written, so this is a documentation fix, not a behaviour one — the chart picks columns by type, never by position. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016KT2a8a4DoNFnpq1QFeEZx
…ot say csq-graph.py draws one measure. scripts/csq-predict.py takes the same JSON and fits an ordinary least squares model of one numeric column against the rest, rendering coefficients with their intervals, a correlation matrix, observed against predicted, and the residuals as one self-contained page. Standard library only: the t and F distributions are computed in the file, so there is still nothing to install. The fitting is the easy part, and is not why the file is this long. A regression over civic data returns a confident-looking answer from almost any set of columns, and most of those answers are artefacts of how the data were counted. So the output is built to withhold them: A coefficient whose interval spans zero is reported as undetermined, never as a small effect — muted on the far side of a zero line, and described as "no association distinguishable from zero". Variance inflation is measured per predictor rather than assumed; past 10 the page says the individual coefficients are arbitrary however good R² looks. When every variable is a count over the same geography it says so, because ward crime, ward 311 calls and ward permits correlate through ward size, and a model of one against the others has rediscovered the population of Chicago. A fit of R² ≈ 1 is treated as a warning rather than a result: on observational data it nearly always means the target was derived arithmetically from a predictor, so the model has recovered a definition. --target is required. Picking it automatically would be picking the question. Nothing is extrapolated beyond the observed range, the word "cause" appears nowhere in the output, and the caveats, exclusions and confidence csq attaches to the query render above the figures. The arithmetic is checked rather than trusted: exact data recovers its coefficients to 1e-10, simple regression matches the closed form for both slope and standard error, residuals come back orthogonal to every predictor at 1e-15, the t critical values match published tables to four decimals, VIF goes infinite on a duplicated predictor, and a singular design is refused instead of fitted. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016KT2a8a4DoNFnpq1QFeEZx
The statistics in csq-predict.py are implemented by hand, because there is
no numpy underneath it. A quietly wrong regression is worse than no
regression — it produces confident output either way — so the parts that
could be silently wrong are now checked against things known
independently of this code:
* simple regression against the closed form, for slope and standard error
* t critical values against published tables, at five degrees of freedom
* the defining property of least squares: residuals orthogonal to every
predictor, and summing to zero
* a model with no noise, which must return its coefficients exactly
* VIF going infinite on a duplicated predictor, and a singular design
being refused rather than fitted
Then the test worth trusting: a relationship is planted alongside a column
of pure noise and read back off the generated page through the real CLI.
The planted coefficients have to land inside their intervals and the noise
column has to be reported, in words, as undetermined. The page is also
checked for external requests, since it is meant to open anywhere.
Verified the suite can fail: dividing the residual variance by the wrong
degrees of freedom — a bug that leaves every coefficient correct and only
the intervals wrong — is caught by the closed-form check, and the run
exits 1.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016KT2a8a4DoNFnpq1QFeEZx
…count Three things, all found by using the tool rather than reading it. A few rows can carry the whole fit, and nothing said so. Greenwich 2016 is the case: 10 of 991 sales carried 91% of the variation in sale price, so every coefficient on the page was a statement about ten houses while the page reported p < 0.001 and looked ordinary. The share of variance held by the top rows is now measured and reported whenever a small minority holds a large part of it. Calibrated against three datasets: it fires on Greenwich, fires on Chicago community areas (3 of 77 carrying 37%, which is real concentration), and stays quiet on evenly spread data. The all-counts warning asserted something it cannot know. Dollar amounts are non-negative whole numbers too, so a model of sale price against assessed value was told to "normalise by population or area" — advice that makes no sense for prices. A warning that is sometimes plainly wrong teaches readers to skip the block it sits in. The detection is unchanged; the claim is now conditional on the values actually being counts, which is all the evidence supports. And an exactly-fitting model crashed. Zero residual variance divided by zero in the F statistic — reachable with integer data, as a rate against its own numerator, which is exactly the case the R² > 0.999 notice exists to catch. Crashing on it was the worst available response. F is now infinite, its p-value undefined, and the tautology notice does the talking. The self-test grows from 35 checks to 39, covering both directions of the leverage warning (it must also stay quiet), the hedged wording, and the exact-fit case that crashed. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_016KT2a8a4DoNFnpq1QFeEZx
fix(scripts): keep the axis around the data, and off the label column
feat(scripts): model several variables, and state what the model cannot say
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Twenty-seven commits spanning three related pieces of work: the modes framework that turns csq from a sync tool into an analysis tool, a set of correctness fixes to sync and MCP found by exercising it, and
csq web, a browser interface for the result.Modes — curated analysis profiles
A mode bundles the datasets a civic question needs, the SQL that answers it, and the caveats that keep the answer honest. Four ship:
corruption(procurement and influence trails),police(civilian oversight),ranking(per-capita city comparison), andresearch(provenance and data-quality due diligence, which reads only the_csqbookkeeping schema and so works on any portal). A test fails the build if a mode declares no caveats — a number without its caveat is how civic data gets misread.Modes are decoupled from portals through concepts and bindings: a mode declares the logical tables it needs, and each portal supplies its own answer. Without that indirection, "police monitoring" really means "Chicago police monitoring" and every new city is a code change. Bindings carry a column map, and a non-empty map is authoritative — a column absent from it is unavailable, not null. NYPD's complaint extract records no arrest flag, so New York is excluded from arrest-share by name with a reason rather than rendered as 0%, which would be indistinguishable from a city that makes no arrests.
rankingwas reworked on the same principle. It previously compared dataset counts and sync freshness — open-data transparency dressed up as a city comparison. It now compares real indicators normalised per resident, and three rules are enforced in code rather than documented: no composite score, absent data is never a good result, and raw counts are never compared across cities.Correctness fixes
fix(socrata)— a connection reset mid-response-body arrives after a200, so it read as a JSON decode error and was never retried. This is what killed the Chicago and New York ranking syncs at offsets 130k–245k.fix(sync)— staging tables were dropped only on a successful swap, so every failed run leaked one permanently; each new run stages under a fresh run ID, so nothing ever reclaimed them.fix(socrata)— the catalog read arowsUpdatedAtfield that does not exist, leaving_csq.catalog.updated_atnull on every row. Now readsdata_updated_at, verified live.fix(mcpserver)—list_datasetssynthesised atable_namefor datasets that were never synced, anddescribe_datasetthen queried a table that had never existed. Both now reportsyncedhonestly.fix(modes)— DOB publishesissuance_dateas text holdingMM/DD/YYYY; permit-activity could not run at all against it.perf(socrata)— pagination moved from$offsetto seeking on:id.$offsetmakes the portal scan and discard every preceding row, so page cost grows with depth and a sync's total cost grows quadratically. Measured against live portals: one 5,000-row page of Chicago crimes took 5.0s at offset 0, 8.4s at offset 1,000,000, and 36.3s at offset 2,500,000; NYCnypd_complaintstook 13.7s at offset 3,000,000 and stopped responding entirely past ~3.1M rows, which is where that sync had been dying. Seeking holds every page at the offset-0 cost regardless of depth. It applies only when the stream is ordered by:idwith:idin the projection — csq's default — and falls back to$offsetfor anything else, including an:idwhose shape is unrecognised rather than interpolating it into a predicate.fix(sync)— a killed process left staging tables andrunningrun rows behind forever. The strategies clean up when a sync fails, but nothing executes when the process dies, and each run stages under a fresh ID so nothing later reclaimed the orphans. Two interrupted syncs left 4,595,000 orphaned rows in the Chicago database against 3,372,967 live ones.sync.Runnow sweeps before writing, which is safe because every caller holds the portal write lock — verified in practice when the sweep correctly refused a database whose sync had been restarted in another process.Also
csq queryfor ad-hoc read-only SQL with CSV/JSON/Parquet export, and paging on the MCP list and search tools.csq web — a browser interface
csq webserves the same analyses as a local web page, from the same binary viago:embed— no install step, no node toolchain, no files beside the executable. The CLI remains the complete interface; this is additive. Three views: Analyses (each mode with a readiness dot, so an unsynced analysis is never mistaken for one that found nothing), Explore data, and Data health. With a paired--config, or from the built-in city picker, the page downloads the datasets an analysis needs with live per-dataset progress; downloads take the same advisory lockcsq synctakes and one runs at a time. Results sort, filter, and export, and any mode renders to a self-contained HTML report — inline SVG, no scripts, no external requests.Two properties are enforced in code because they are the ones most likely to drift. The browser cannot send SQL: every endpoint takes a mode name and a query name, so there is no injection surface and the page runs exactly what
csq modes runruns. And caveats and city exclusions travel in the same payload as the rows, with no code path that renders a table without them. The decisions behind both live in a newinternal/analysispackage so the CLI and the page cannot disagree.Verification
Exercised against live portals, not only fixtures: two full 235,860-row Chicago downloads driven from the UI, and a cold start from an empty directory — no database, config, or flags — through the city picker to a queryable analysis whose generated YAML still drives the CLI. Cook County's five State's Attorney datasets (~3.2M rows) were synced and profiled;
research --query date-range-sqlon that corpus reports asentence_datereaching the year 2921 and anarrest_datestarting in 1915, which is the class of upstream defect these modes exist to surface.gofmt,go vet, the full suite, and the race detector on the new packages all pass.Worth a reviewer's attention
A DuckDB
READ_ONLYattach is a snapshot bound at attach time and never sees writes made through a read-write handle in the same process, so the server closes the writer and re-attaches after a sync. Without that, a download succeeds and the UI goes on reporting no data — the most confusing possible outcome.🤖 Generated with Claude Code
https://claude.ai/code/session_01WCD2ZY9zZPPnshapH6cog8