34 Commits
Author SHA1 Message Date
CatoandClaude Opus 5.5 493f7f7cc0 feat(programmes): public funding programmes beside foundations and investors (#223)
* wip(programmes): the programme schema; the theme matcher moves into the app

Work in progress on a branch with no pull request yet. The theme matcher
(keywords and compounds of an organisation's themes) moves from scripts/lib
into src/lib/domain so public programmes are matched by the same rule as
foundations; the script re-exports it. The programme schema follows the
investor register: every fact with its page, date and verbatim sentence.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtMwPqoAJ2pHxdSn3t

* feat(programmes): public funding programmes beside foundations and investors

Seven federal, cantonal and EU programmes, read on 2026-12-01 from the
operators' own pages: Innosuisse (three instruments), the EIC Accelerator
via Euresearch, the federal media-literacy grants (Jugend und Medien), and
the canton of Zurich's integration projects and charitable fund. Every fact
carries the page, the day and the sentence it rests on; every sentence was
checked against the downloaded page. What a page does not say is named with
the reason; six programmes looked for and not entered are listed with why.

- Table fundraising_programmes (migration 0023), import script (dry run
  unless --write), and a re-check script that reads every cited page again
  and fails when a quoted sentence is gone.
- Workspace page: open programmes first, then those whose own words hit the
  organisation's themes, by the same keyword rule as the register screen
  (moved to src/lib/domain/theme-match.ts). A programme that asks for an
  organisation is marked for one that has no legal entity yet; programmes
  are now one of the kinds the legal-standing notice names.
- A grant Vorhaben links to the programmes as well as the foundations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtMwPqoAJ2pHxdSn3t

* feat(programmes): the seven programmes load with the deploy

Migration 0024 inserts the rows of data/programmes/seed-2026-12-01.json, so
the register is filled when this goes live and nobody runs an import by
hand. A test keeps the migration identical to the sourced data file; ON
CONFLICT DO NOTHING never puts a row back to this first reading once a
later re-check has updated it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtMwPqoAJ2pHxdSn3t

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-12-01 14:28:49 +01:00
CatoandClaude Fable 5.2 b6f04bb60b feat(themes): each organisation's themes are its own data (#214)
* feat(themes): each organisation's themes are its own data

ThemeId was a code enum of one organisation's seven fields of work, and every
foundation, badge, filter, score, Gesuch and triage prompt on the platform was
described in it. An assessment stored in another organisation's theme ids
failed to parse and disappeared from its pages.

Themes are now org_content['themes'] per organisation (shape and lookups in
src/lib/schemas/theme.ts), authored in org-context/<org>/themes.json. Each
theme carries its label, the story section and HOW slot a Gesuch draws on,
whether it is a region, and the keywords the register is classified with; the
order is the order the organisation leads with. The story is bound to its
organisation's vocabulary, so a composer cannot describe a foundation in
another organisation's themes. HOW competency slots are the organisation's own.

The triage prompts are built from the organisation's own brief
(org_content['triage-brief']) and themes. pipeline-graduate phase 1 reads the
organisation's assessments instead of a column migration 0015 dropped.

Migration 0020 writes the first tenant's vocabulary and brief, ported
unchanged from the code: the classifier gives identical themes on all 16,781
foundations of the 29 Nov register, and a test holds the story mapping and the
migration to the files. One put script (org-content:put) stores themes, triage
brief and raise profile from org-context.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019MDtmtMwPqoAJ2pHxdSn3t

* feat(themes): the workspace reads the organisation's own themes

The tools moved to the workspace while this was under review; its layout
now loads the theme vocabulary of the organisation in the URL.

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

* docs(claude): the quick reference describes the workspace

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-30 23:40:20 +01:00
CatoandClaude Fable 5.2 0265f84a15 feat: investor register beside foundations, and BiasLens as a seeker (#213)
* docs(funders): how funder generalises from foundation to investor, lender and donor

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

* feat(orgs): BiasLens as a seeker, and a keyword screen any organisation can run

Adds org-context/biaslens (sourced fact sheet, its own screening rules, four
media grant-makers checked on their own sites), scripts/org-screen.ts with a
pure, tested screen in scripts/lib, and the registered purpose in the Zefix
download so the screen runs from the public register without a database.

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

* feat(investors): a hand-curated investor register with sourced fields, fit and memo

Adds fundraising_investors (migration 0019) beside the foundation register.
Every fact is a value with the URL it was read from and the date; the schema
refuses a fact without a source and has no field for a person. Fit compares an
investor with the organisation's raise profile and answers unknown, never
match, where either side has no value. The one-page memo is composed from
recorded facts only, is internal, and nothing sends it.

Seeds nine investors read on their own sites on 2026-11-29 and BiasLens's
raise profile. Import and raise-profile scripts are dry runs unless --write.

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

* docs(funders): Hirnli as its own product, as a proposal; draft journal entry for 29 Nov

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

* feat(investors): the investor pages live in the workspace

The tools moved to /o/<slug>/fundraising while this was under review. The
investor list and detail pages move with them, the workspace menu gets
«Investoren», and the docs name the new place.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-30 22:50:22 +01:00
CatoandClaude Opus 5.5 5729c5bb84 fix(nav): logo, language and theme controls are 44px targets (#124)
* fix(nav): logo, language and theme controls are 44px targets

The header's logo link was 40px tall and the DE and theme toggles 36px
(h-9), under the fleet's 44px floor (nav contract rule 3). The toggles are
shared with the mobile menu and the platform layout, so all of them move
together; the logo link gets min-h-11.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

* fix(test): a fresh 404 Response per call in the chain-walk test

main has been red since #122 bumped ai-kit: the test handed every link the
SAME Response, ai-kit now reads a 404's body, and a body can be read once -
so the second link threw a non-LinkFailure and the walk stopped at 2 of 4
calls. The code under test was right; the mock was not.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>

---------

Signed-off-by: Cato <41178744+catomean@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-09-26 00:21:55 -07:00
CatoandClaude Fable 5.1 c5700392ab refactor(scripts): one splitFoundationPatch, imported from the app (#118)
scripts/lib/assessment-write.ts restated splitFoundationPatch line for line
from src/lib/db/assessment-write.ts. The two files are not otherwise the same
module — the scripts one writes through the raw pg client because tsx
one-shots run outside Next, the app one through Drizzle — so the client-bound
writers stay where they are, but the pure function that decides which keys are
analysis had no reason to exist twice. The six ingestion scripts and the test
now import it from the app module (grant-org-membership.ts already imports
src/lib/db from a script, and the db client is lazy, so the import has no
side effect). 2 copies → 1.


Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-14 22:25:08 -07:00
CatoandClaude Opus 5 057525cf38 feat(health): /api/health/ai — and a 401 now costs one request per vendor, not one per model (#107)
The only AI route here sits behind the shared internal Basic Auth, and
the rest of the AI surface is research scripts with no HTTP entry point
at all. So "does the chain work?" could only be answered by knowing the
internal password, or by running a script by hand. /api/health reports
`llm`, but that says what happened the LAST time something called a
provider — after a deploy it is "unknown", and unknown is what it stays.

  GET /api/health/ai            free. What the last real call did.
  GET /api/health/ai?probe=1    a real call. 200 or 503. Needs the secret.

It probes THIS app's chain: `ask` (ai-kit 0.15.0) calls callGroq, the
same function the gesuch-section route and every research script use.

DELIBERATELY OUTSIDE THE BASIC AUTH WALL — it is not under /api/ai. Its
callers are uptime monitors and deploy scripts, which have no password to
present, so it carries its own gate: AI_PROBE_SECRET, constant-time
compared inside ai-kit. Without it, 401; with no secret configured at
all, 501 — a deployment that forgets to set one cannot be made to spend
money by a stranger.

THE ai-kit BUMP CHANGED REAL BEHAVIOUR, and two existing tests caught it.
0.13.0 made a rejected key condemn the whole VENDOR: a 401 says "not
you", and every remaining model there presents the identical credential,
so walking them spends a request each to be told the same thing. Both
tests asserted the old, wasteful shape (CHAIN_MODEL_COUNT calls on a
401). They now assert one attempt per vendor — and a new test pins the
BOUNDARY that keeps the skip honest: a 404 still walks every model at
that vendor, because a retired id is a fact about one model, and widening
the skip would turn the chain back into the pin it replaced.

verify green — 1118 tests, 75 files.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-08 12:41:48 -07:00
CatoandClaude Opus 5 6ecd513605 fix(scoring): fit scores follow the applicant's priorities, not the module's (#104)
`THEME_HIERARCHY` names one organisation's core fields of work — labour
integration, circular economy, digital education, digital sovereignty. A theme
in `core` scores 1.5x, one in `secondary` 0.5x, and every tenant's scoring used
that list.

It reaches production twice, and I had to be corrected on both by the code:

  - the seven ingest and enrichment scripts call `computeFitScore`, which
    writes the number into an organisation's assessment. That number decides
    which foundations it is told to approach.
  - the "Fit" tab explains the same number back, through `explainFitScore`. It
    renders client-side, which is why curling the page never showed it.

It stayed invisible because only one organisation has ever run research, so the
priorities compiled into the module were that organisation's and the scores were
right by coincidence. A second customer turns "right for the only user" into
"wrong for a user".

`org_scoring` has held a complete per-organisation engine since migration 0007
and nothing read it — the fifth producer with no consumer found in this work.
It is read now, and the stored row's thematic categories are byte-identical to
the module's, so the first customer's scores do not move. An organisation with
no row gets one flat category covering every theme id: a worse fit signal than a
stated ranking, and a much better one than somebody else's.

The parameter is required rather than defaulted. A default would have been
silent — every existing caller would keep compiling and quietly change what it
weighted. Making it explicit is what surfaced that two ingest scripts wrote
per-organisation fit scores without resolving an organisation at all, which is
how they came to score with whatever was compiled in.

`ThemeCategory` is exported from the config and used by the reader, the engine
and the scripts. The first draft declared its own and the two drifted on `cap`
within the hour.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 10:11:33 -07:00
CatoandClaude Opus 5 34e7bc73bf refactor(ai): complete() owns the fetch — the 429 body was read and thrown away (#88)
This client was already careful: it walked ai-kit's cross-vendor chain
with tryChain, gave each link its own deadline, and treated an empty
body as a failure. That is more than most of this fleet managed.

What it could not do was READ a 429. The message was
`<vendor> API HTTP 429: <first 200 chars>` — the body was fetched,
truncated into a string, and read by nothing. So a spent daily budget
and a one-second burst produced the same message and the same
behaviour, and only one of them can be fixed by trying again.

complete() classifies it:

  capacity — a burst. Demoting to the next link is right.
  daily    — the vendor's whole ORG-WIDE budget is spent. Its other
             models draw on the same meter, so trying them buys a dead
             round trip and the identical error. The vendor is condemned
             for the walk.
  size     — one request exceeded the per-minute allowance by itself.
             Every link below has a SMALLER ceiling, so demoting is
             strictly worse. The walk stops and the caller is told to
             send less.

callGroqOnce is gone entirely (-70 lines): no fetch, no key plumbing, no
AbortController. The explicit-model path is now a chain of exactly one,
so it is still called once and alone as its doc promises — while still
reading a 429 properly, which is the point of routing even a single call
through the engine.

Two tests now pin the taxonomy: a DAILY 429 asks Groq exactly ONCE and
crosses to OpenRouter; a SIZE 429 makes exactly ONE request in total.

TEST MOCKS: `{ ok, json }` literals encoded an assumption about HOW the
client reads a body and broke the moment it read the text first. Real
Response objects now, built per call — one Response body can be read
only once, so a single shared instance makes link two fail with "Body
has already been read", a fake failure in front of the real one, inside
the tests that check the fallback.

verify green: format, lint, umlauts, typecheck, 1071 tests, build.


Claude-Session: https://claude.ai/code/session_01NHDLTKGirKU7He8q2YR2y4

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-07 04:25:07 +00:00
9d0c08120d refactor(tenant): which host belongs to which customer becomes a row (#79)
`HOST_TENANTS` was a TypeScript object literal, so taking on a customer — or
removing one — meant editing, reviewing and deploying the application. A
platform that has to be rebuilt to accept a customer is not a platform, and the
map was also the last place a tenant's identity was hard-coded outside its own
row.

Host → tenant is now `org_domains`. Middleware cannot read it (Edge runtime, no
node-postgres), so it stops resolving the tenant altogether: it forwards the
normalised Host as `x-tenant-host` and `getCurrentOrgId()` does the lookup in
the Node runtime, cached per request.

THE FALLBACK IS GONE, and that is the substantive change. `getCurrentOrgId()`
ended in `?? DEFAULT_TENANT_ID`, so an unrecognised Host — a stray domain, a
probe, a not-yet-mapped customer — silently rendered the first customer's site
AND scoped every query to its data. The failure mode of tenant resolution must
not be "serve somebody". It now throws, the same choice `getTenantById` already
made for a missing row. The old test asserted the opposite ("an unknown host
must land on a real tenant, never undefined"); that reasoning was right about
the danger and wrong about the remedy, and the rewritten file says so.

Three other places named a customer to get their work done:

- The platform chrome linked to "the first tenant's live site" via a hard-coded
  id. A product page that names one customer is that customer's page, and it
  made the platform surface unrenderable without that tenant existing.
- The platform funnel loaded the REFERENCE tenant's foundations, so the product
  page described one customer's research as the platform's.
  `getRegistryFoundations()` reads the shared register with nobody's
  assessments, which is what the platform has actually done: nothing.
- Both cron jobs pinned the tenant, so the data-quality report and deadline
  reminders ran for one customer and, silently, never for anyone else. Which
  tenant is now data — the organisation that has stated a `fundraisingEmail`,
  which is the opt-in it already made. Fanning out to several still means
  looping their bodies and starting to mail customers who receive nothing
  today; `lib/tenant/reporting.ts` is the seam, and says so.

Adds the ratchet this migration is measured by. The reference tenant is named
353 times across 119 files; `no-tenant-traces.test.ts` pins each spelling's
count with an exact assertion, so a reduction must be recorded and a rise
fails the build. Down 12 in this commit.

SEQUENCING: 0016 was applied to production before this merges. The resolver
reads `org_domains` on every request, so code landing first would 500 the whole
site. Data first here — the reverse of the tagline change, and for the same
reason: whichever side is depended upon goes first.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 13:47:04 +00:00
60999a74dd Gesuch composers take the organisation; documents render whoever they were composed for (#58)
* refactor(tenant): the Gesuch composers take the organisation as an argument

Five domain modules imported ORG_PROFILE and wrote it into Gesuch prose — the
cover letter opening, the subject line a foundation sees first in its inbox, the
bridge sentence, the fit narrative, and the prompt pasted into ChatGPT. A
composer that reaches for its own organisation can only ever write for one, and
this is the worst place for that: the output looks finished and reads well.

The tenant is now the first parameter of composeGesuch, composeGesuchDokument,
composeAnschreibenText, buildDynamicOpening, buildFoundationBridge,
generateFitNarrative and buildExternalPrompt, threaded from the 13 call sites
that resolve it — pages and route handlers await getTenant(), client components
(FieldRow, GesuchPageClient) read the provider, and scripts/gesuch-audit.ts
loads it explicitly.

Required, with no default. A default is exactly how the single-tenant fallback
returns, and it would return silently.

Absence is handled where it changes the sentence:

- Three openings are built around missionSummary ("in der Verbindung von …").
  A tenant that has not written one gets the generic template opening instead —
  less tailored, but true.
- landingPageUrl, which is printed in a Gesuch going to a foundation, is
  relative when a tenant has no site rather than absolute against another
  organisation's domain.
- buildExternalPrompt omits the Kernbereiche block rather than emitting an
  empty bullet list a model would read as "this organisation does nothing".

scripts/lib/tenant.ts is the scripts-side reader, and deliberately reuses
parseTenant from src/lib/tenant/profile.ts — a second parser would be a second
definition of what a tenant is.

Four tests asserted the literal 'Revamp-IT'. That assertion is why the imports
survived this long: the fixture and the import agreed, so it passed either way.
They now compose with two different tenants and require two different strings —
verified by mutation, which fails both.

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

* refactor(tenant): the Gesuch documents render whoever they were composed for

Thirteen renderers — eight page sections and five PDF components, including the
5-page Gesuch, the one-pager, the Wirkungsbericht and the pitch deck — read the
organisation's name, address, phone and website from the compile-time
ORG_PROFILE. These are the documents that get posted to a foundation, so a
wrong name here is the failure mode that is hardest to notice and worst to send.

THE COMPOSED DOCUMENT CARRIES ITS AUTHOR

`ComposedGesuch` gains `tenant`. The alternative — a second `tenant` prop beside
`dok` at every render site — would have made it possible to render a document
composed for one organisation under another's name, with both props present,
both well-typed and nothing to catch it. Keeping the content and its author in
one value makes that unrepresentable rather than merely unlikely.

The renderers that receive no composed object take what they actually use:
GesuchHeroSection and GesuchContactSection an `orgName`, the report PDFs a
`tenant` prop from their route (they run inside renderToStream, where there is
no provider to read).

ABSENCE, WHERE IT CHANGES THE OUTPUT

Every optional field is guarded at each use, per the rule added to
docs/TENANT-MIGRATION-MAP.md after the last batch shipped two empty labels:

- The Kurzportrait's "einsehbar unter <site>" claim is dropped entirely without
  a site. The sentence tells a foundation where to verify the numbers; without
  an address there is nothing to verify, and a trailing "unter ." reads worse
  than saying nothing.
- The submit section's field map is a crib sheet somebody pastes into a
  foundation's online form, so a row with no value is worse than a missing row.
  Empty rows are filtered out rather than rendered.
- Letterhead and footer lines are joined from what exists, so no document shows
  " |  | " or "kontakt@…  ·   ·  " around a hole.

MIDDLEWARE

The Basic-Auth realm named the first tenant, so every other tenant's browser
prompted for a password under an unrelated organisation's name. It runs on the
Edge runtime where the tenant reader cannot go, so it now names the platform —
which is the honest answer: it is the platform asking.

ORG_PROFILE consumers: 67 files at the start of this migration, 9 now. The rest
are the config content modules, which move with org_content.

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

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-04 05:48:01 -07:00
b8ea92eccb fix(foundations): write assessments where the read looks, and fail loudly when it can't (#50)
Splitting foundations into a shared registry and per-org assessments (#47)
moved the READ. Every write path still wrote fitScore, priority, themes,
tagline and researchNotes into config_data, which composeFoundation now
strips. So editing research notes returned 200 and changed nothing visible,
and seven ingestion scripts reported rows updated while producing no effect.
A failure with no error to notice.

Write paths now split a Foundation-shaped patch by ANALYSIS_FIELDS — the same
schema-derived list the read uses, so the two cannot disagree about where a
field lives:

  API      POST/PUT/PATCH/import — registry to config_data, analysis to the
           asking org's assessment row.
  Scripts  foundation-upsert, zefix-ingest, pipeline-incremental,
           ingest-triage, pipeline-graduate, bulk-import-batches,
           dedupe-by-uid.

Four of those scripts had no org id at all and updated rows by slug alone.
They take --org now: an assessment has an owner by construction, so the
question can no longer go unanswered.

Three things the split changed that are easy to miss, and are handled:

- bulk-import-batches decides "fill only what is empty" and "raise a fit
  score, never lower it" against current values. Reading config_data alone
  would show them all absent, so every rule protecting existing work would
  pass and overwrite it. It now merges against both halves.
- foundation-upsert read its own row back and parsed it as a Foundation to
  correct priority. That parse can no longer succeed on the blob alone, so
  the correction would have silently stopped running. It reads through the
  shared composition instead.
- dedupe merges two registry rows, but the opinions attached to them belong
  to tenants, possibly several. It now carries every org's assessment onto
  the keeper rather than archiving them with the loser.

Also fixes a production outage found while verifying #47 against its baseline.

Migration 0012 created the assessments table as the migrating role; the app
connects as a lesser one, and a new table grants nobody but its owner. Every
read raised 42501, the repo caught it, logged "DB unreachable", and returned
[]. Production served HTTP 200 everywhere and showed a customer with 1,683
researched foundations that it had none; /api/export/foundations returned a
header row and nothing else. Nothing alerted.

Both halves of that are closed:

- 0014 grants the app role access, deriving the role name from the existing
  grantee on fundraising_foundations so it is correct on any deployment, and
  sets default privileges so the next new table cannot repeat it.
- foundations-repo rethrows SQLSTATE class 42 instead of degrading. Code and
  schema disagreeing is a deploy defect, true again on the next request; only
  a genuinely transient failure falls back to an empty list.

Guarded by tests, both proven to fail under mutation: the scripts' column map
must equal ANALYSIS_FIELDS, and the class-42 rule is pinned against both the
codes it must catch and the ones it must not.

The flat fit_score/priority/research_date/research_depth columns on
fundraising_foundations are still written, from one helper, because the list
endpoint still filters on them — not writing them would recreate the drift
migration 0003's trigger exists to prevent. They go when the columns do.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 17:23:57 -07:00
3c1b9612fe refactor(deps): ai-kit comes from npm — @bitbaum/ai-kit ^0.6.2 (#48)
Claude-Session: https://claude.ai/code/session_01WqKqMnHQHSmkGFfc5t7Rxn

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-03 15:26:49 +00:00
79ef08f125 feat(tenant): read a foundation as the asking organisation sees it (#47)
* feat(tenant): separate what a foundation is from what an org thinks of it

`fundraising_foundations` has PRIMARY KEY (id) — the slug alone. It can hold
one row per foundation for all tenants combined, so the `org_id` column reads
like tenancy but cannot deliver it: a second organisation assessing
"volkart-stiftung" collides with the first organisation's row. All 16,623 rows
being Revamp-IT's is why this never surfaced. It is not a latent
inefficiency — it is the reason a second tenant cannot have foundation data.

Migration 0012 adds fundraising_foundation_assessments, keyed
(org_id, foundation_id), and backfills it from config_data. The data decided
which fields go where:

  * `type` (Schmuki A/B/C/D) reads relational but is not — the stored
    typeReasoning describes the foundation ("Potente, professionalisierte
    Förderstiftung"), so it is shared, and 16,623 classifications stop being
    re-derived per tenant.
  * `archived` is a vintage, not a judgement: 1,116 of the 1,117 archived rows
    carry the legacy fit/needsResearch keys and no unarchived row does. Shared.
  * fitScore, priority, themes, tagline and researchNotes are one org's
    opinion. researchNotes says so itself — "Relevante Übereinstimmung mit
    Revamp-IT-Themen (Fit 2/3)" — which is also why it is confidential: which
    funders you rate highly is not something you show another fundraiser.

Applied to production inside a transaction that verified every extracted value
against its blob and would have aborted on any mismatch: 16,623 rows exact.

The new table also drops a duplication. In `foundations`, fit_score, priority,
research_date and research_depth exist twice — in config_data and as flat
columns — reconciled by the trigger added in 0003 after 535 rows had drifted
apart in production. Here each value is a column and nothing else, so there is
nothing to sync.

Additive on purpose: nothing reads the new table yet and the values remain in
config_data. Readers move next; only then are they removed from the blob. No
single step both moves data and changes what the app reads.

Also fixes an active bug this work surfaced. `POST /api/foundations` and
`POST /api/foundations/import` never set orgId. That was invisible while the
column defaulted to 'revamp-it'; since 0011 dropped that default it meant every
foundation created through the admin API belonged to nobody — invisible to a
tenant-scoped read, and unable to carry an assessment at all. Both now resolve
the tenant per request.

Rather than add a test for that shape, 0013 makes org_id NOT NULL, which every
other tenant-scoped table already was. Drizzle then infers it as required and an
insert that forgets the tenant fails to compile. A grep test finds the shapes I
thought to look for; the type checker sees every insert there will ever be.

Verified safe first: all 16,623 rows carry an org_id, and all five insert sites
(two Drizzle, three raw SQL in the ingestion scripts) set it explicitly.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

* feat(tenant): read a foundation as the asking organisation sees it

Until now no read filtered by org at all — `org_id` was a column nothing ever
selected on. One customer's fit scores, priorities and private research notes
were simply what every reader got, on every page.

A read now composes the shared registry row with the requesting tenant's own
assessment, producing the same Foundation shape the app already consumes, so
none of the ~56 consumers change.

LEFT JOIN, not INNER. A tenant browses the whole registry and its own
assessments overlay it; an inner join would show a new customer an empty
product, when the registry of researched foundations is the thing they came
for.

Two traps handled explicitly:

  * The cache key now includes the org. A per-tenant result under a shared key
    is the same cross-tenant leak as an unscoped query, arriving by a route
    that is much harder to see — the first tenant to warm the cache would
    decide what every other tenant reads.
  * `config_data` still holds Revamp-IT's analysis values, since 0012 copied
    without deleting. So the composition strips the analysis keys and applies
    the assessment, rather than merging over the blob, where a tenant with no
    assessment would inherit whoever researched the foundation first.

`type` moves to the registry schema, the code half of the decision 0012 made
in the data: the stored reasoning describes the foundation, not the
relationship.

The composition is shared with the pipeline scripts rather than written twice.
That duplication was already costing something: the two readers had drifted on
their WHERE clause — the app matched `archived = false`, the scripts accepted
`archived = false OR archived IS NULL` — so an audit script and the page it
audited could disagree about which foundations exist. Both now use one clause.

`scripts/lib/foundations.ts` takes a required orgId. An audit that cannot say
whose data it examined reports one tenant's numbers as everyone's. TypeScript
named all six callers; five scripts now use requireOrgId() and the integrity
test names the tenant whose data it asserts about.

The platform page reads getReferenceTenantFoundations() explicitly. It belongs
to no tenant but computeFunnelStats is not tenant-neutral — it counts fit
distribution, themes and research depth beside registry facts — so that page
reports one customer's work as the platform's. Unchanged behaviour, but now
greppable instead of arriving through a default. What it should report is a
product question.

On the test, and a correction worth recording: the obvious guard here does not
work. Removing the analysis-key deletion and checking for leakage passes
against the broken code, because UNASSESSED_ANALYSIS names all nine fields and
the spread already overrides each one. I only found that by mutating the
function and watching the test stay green. The assertion that does hold is that
its keys equal ANALYSIS_FIELDS — the real failure is a field added to
analysisSchema without a default here — and that one was verified to fail under
mutation before being kept.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

---------

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 14:51:15 +00:00
0dc75feafb fix(tenant): no column may default to the first tenant (#43)
Every tenant-scoped org_id carried default('revamp-it'), and three ingestion
scripts wrote that literal. With one customer it is invisible; with two, any
write that forgets to say whose data it is files the row under Revamp-IT and
nothing afterwards distinguishes it. The attribution is not wrong in a
recoverable way — it is gone.

'Whose data is this?' has no sensible fallback, so an unanswered question now
stops the write. Removing the Drizzle defaults made TypeScript name five write
paths that had never said whose data they created, including three
activity-log writes that would have logged evig's actions as Revamp-IT's.
Migration 0011 drops the defaults in the database too, so an unattributed
insert is rejected rather than silently attributed (verified against the live
DB: null value in column org_id violates not-null constraint).

The ingestion scripts now take --org / HIRNLI_ORG_ID and refuse to start
without one.

Two further findings while doing it:

  config_data never contained orgId on ANY of the 16,623 rows — the Zod
  .default('revamp-it') manufactured it on every parse, so every foundation
  reported itself as Revamp-IT's regardless of its actual column. The composed
  schema then did .omit({ orgId: true }), stripping the invented value right
  back out. The codebase already knew the field did not belong; it is gone.

  getTenantByHost() and the static TENANTS map are deleted. They were a SECOND
  reader of tenant identity built from the compile-time constant, and they
  returned undefined for evig — a tenant with a profile, a logo and a
  membership but deliberately no hardcoded entry. One reader, reading the
  database.

evig also gains a host, having had an identity before it had an address.


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-03 11:53:46 +00:00
84ea4a80e6 fix(ai): cross-vendor fallback for AI calls, not just cross-model at Groq (#33)
`GROQ_PROVIDER = freeChain('HIRNLI')[0]` took only the first entry (Groq)
from ai-kit's cross-vendor chain and discarded OpenRouter entirely.
`usableChain` was never imported or called, and `.env.local.example` had no
slot for `OPENROUTER_API_KEY` — the fallback vendor wasn't wired into config
at all. Every model in the existing "fallback" shares Groq's org-wide daily
budget, so a Groq-wide outage or budget exhaustion took this app's AI fully
dead with nowhere else to go — exactly the scheduled-outage class ai-kit
exists to prevent.

callGroq() now walks `usableChain(freeChain('HIRNLI'), env)` via `tryChain`
when no explicit model is given, so a deployment with both GROQ_API_KEY and
OPENROUTER_API_KEY configured survives a total Groq outage. An explicit
model/alias (GROQ_MODELS, the `--model=8b`/`70b` CLI contract) still targets
Groq specifically, alone — that pin's whole point is "call this model", not
"start the chain elsewhere".

- scripts/lib/groq-client.ts: build the real two-vendor chain and walk it
- scripts/lib/groq-client.test.ts: pin the cross-vendor fallback and update
  the "no key" test for the new multi-vendor error message
- .env.local.example: document OPENROUTER_API_KEY as the fallback vendor


Claude-Session: https://claude.ai/code/session_01HVwg8DKHQktxJuHeLM3xpG

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-02 08:32:45 +00:00
GandClaude Opus 5 dae6e3544c chore: add a formatter (#27)
* chore: add a formatter, matching the style this repo already writes

singleQuote=true was chosen by counting this repo's own
imports, not by fleet decree. The fleet is genuinely split and the two repos
that already had a .prettierrc disagreed with each other, so there was no
standard to restore. Quote style does not cross repo boundaries; having a
gate does.

Markdown is ignored for now — prettier rewraps prose, which would bury the
real diff.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* style: format with prettier (399 files)

Mechanical. No behaviour change. This SHA is listed in
.git-blame-ignore-revs so `git blame` skips it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* chore: teach git blame to skip the reformat

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* fix(lint): reattach a disable directive the reformat detached

eslint-disable-next-line binds to a line number, so reformatting can silently
break it. This effect was written on one line:

  // eslint-disable-next-line react-hooks/set-state-in-effect
  useEffect(() => { setMounted(true); }, []);

prettier expanded it to a block body, which moved setMounted(true) down a line
and out from under the directive. The rule reports at the setState call, not at
the useEffect, so the suppression stopped applying and the build failed on a
rule the author had deliberately silenced.

Moving the directive inside the effect binds it to the call itself, where
reflowing cannot separate them. The other six directives in src/ still bind.

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-29 11:02:00 +00:00
927ea5a981 feat: adopt ai-kit's tryChain + createHealthTracker; add /api/health (#26)
hirnli has already been silently taken down once by a single retired
Groq model id -- every route and script here called ONE pinned model,
once, with nothing between that and total failure. This closes that
gap the same way botsmann's did this session.

- scripts/lib/groq-client.ts: callGroq now walks ai-kit's fallback
  chain for Groq via tryChain when the caller leaves the model
  unspecified, instead of calling one hardcoded id. GROQ_MODELS' alias
  table is now derived FROM that chain rather than hardcoding the same
  ids a second time. An explicit model/alias is still honoured as-is
  and alone, unchanged.
- src/app/api/ai/gesuch-section/route.ts: this route hand-rolled its
  OWN separate Groq fetch, with its own hardcoded model id -- a second
  copy of exactly what groq-client.ts already did, despite that
  file's own docstring saying it was "extracted from" this route. Now
  calls callGroq directly; ~50 lines of duplicated fetch/error-handling
  code deleted.
- src/lib/llm-health.ts + src/app/api/health/route.ts (both new):
  hirnli had no health endpoint at all. Records success/failure around
  the gesuch-section route via ai-kit's createHealthTracker, exposed
  at /api/health (liveness) and /api/health?strict=1 (readiness --
  503 only when the LLM chain itself is down, never on a restart-proof
  problem).

ai-kit bumped to v0.5.0. Full verify green: lint, lint:umlauts,
typecheck, 889 tests (17 new), production build.

Co-authored-by: Mao Nakamoto <41178744+maonakamoto@users.noreply.github.com>
Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-08-29 09:14:41 +00:00
GandClaude Opus 5 2ae509ae7c fix(ai): every Groq id here was dead, and the alias table was never consulted (#11)
Two faults met in `scripts/lib/groq-client.ts`, and the second was hidden by
the first.

Groq retired the entire llama-3.x family. That killed the default
`llama-3.3-70b-versatile` — used by this client and, separately, by
`/api/ai/gesuch-section` — and both entries of the `GROQ_MODELS` table. Every
call returned 404 with a perfectly valid key, which the route surfaces to the
user as "AI unavailable".

The second fault is the more interesting one. `website-verifier.ts` calls

    callGroqJSON(..., { maxTokens: 150, temperature: 0.1, model: '8b' })

and `model` went straight into the request body. So those requests asked Groq
for a model literally named "8b". The table mapping `8b` to a real id was
sitting in the same file, consulted by nobody.

That bug was invisible for as long as the first one was true: when every id
404s anyway, sending a nonsense one looks identical from the outside. Fixing
only the ids would have left it in place and looking fixed. `resolveModel` now
translates aliases at the point of the call, and an unrecognised value passes
through untouched so naming a real id directly still works.

The old keys `70b` and `8b` are kept deliberately. `pipeline-graduate.ts
--model=8b` is typed by a human at a terminal, and silently changing what that
accepts is a worse failure than a key whose name now describes a role rather
than a parameter count. `large` and `small` are added as the honest names and
the old two are marked deprecated.

Replacement ids verified present in Groq's live catalogue on 2026-08-27, and now
covered by dotfiles/scripts/ci/model-pin-audit.mjs, which asks Groq daily
whether they still exist. This repo had never appeared in that audit's output
before today — its files were not being opened — which is why two dead ids sat
here unreported.

Seven tests, on the resolution rather than on the ids: whatever goes in, what
comes out must be something a vendor could accept, and no id from the retired
family may survive. Family, not individual ids — the failure was a whole
lineage withdrawn at once, so naming one would pass happily on its sibling.

verify: lint, umlaut check, typecheck, 42 suites / 877 tests.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 23:16:48 +00:00
Mao NakamotoandClaude Opus 4.8 9323d6972e feat(foundations): Phase C — runtime DB read layer replaces build-time sync
- src/lib/db/foundations-repo.ts: live reads via unstable_cache (1h TTL)
- stiftungen-generated.ts build cache eliminated — DB is the only source
  (was: dual-sourced during the migration; SSOT restored)
- prebuild/predev sync hooks removed; build needs no DB access
- SKIP_SYNC escape hatch removed from CI (obsolete)
- docs updated: CLAUDE.md, DATABASE_SETUP, DEPLOYMENT, scripts/README

verify green: lint + umlauts + typecheck + 876 tests (41 files).

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-17 13:55:42 +02:00
Mao NakamotoandClaude Fable 5 5743a7b2ea fix(scripts): port 15 pipeline scripts off the dead Neon driver to pg
The entire ops pipeline (ingest, triage, research, upsert, audit) still used
@neondatabase/serverless against the decommissioned Neon endpoint — broken
since the 2026-06-12 self-host migration. All scripts now share one pg-backed
sql tagged-template client (scripts/lib/db.ts, same call-site API), verified
live against the production DB via SSH tunnel (npm run audit, sync-numbers).

Also: audit-themes + set-confidence moved from src/scripts/ to scripts/,
enrich-addresses-zefix.js (broken one-off) deleted, versioned filenames
dropped (foundation-screen-v3.1 → foundation-screen, research-queue-v2 →
research-queue), @neondatabase/serverless dependency removed.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 14:42:04 +02:00
g-butandClaude Opus 4.7 bd9cb660fa chore(scripts): remove 7 more dead scripts + refresh theme-classifier comment
Continuation of b6df91a + 1a16e5d cleanup. 7 more scripts with
0 real callers (only doc-comment mentions in research notes /
file headers):

  batch-research.ts (416 lines) — superseded by foundation-batch-
    research.ts. theme-classifier.ts mentioned it as "extracted
    from"; that line is now historical and was the only "ref".
  queue-agent-research.ts (105 lines) — orphan
  find-website-hints.ts (39 lines) — orphan
  zefix-dedup.ts (55 lines) — replaced by dedupe-by-uid.ts
    (commit 20f5cf9) which actually closed the cross-language UID
    duplicates this script never caught.
  import-research-results.ts (348 lines) — superseded by
    bulk-import-batches.ts (the active import path).
  backfill-research-method.ts (134 lines) — one-time backfill,
    only mentioned historically in PIPELINE-LEARNINGS.md.
  backfill-themes.ts (129 lines) — one-time backfill, no callers.

Also refreshed scripts/lib/theme-classifier.ts header — used to
say "Used by: batch-research.ts, esa-bulk-ingest.ts, future
pipeline scripts"; both named consumers no longer exist. Updated
to the actual current consumers (zhaw-ingest, bulk-enrich,
zefix-ingest, foundation-research-queue-v2, pipeline-incremental,
pipeline-graduate).

Kept research-agent.ts (354 lines, 4-phase enrichment tool) — has
0 references but is substantial enough that it might be invoked
manually. Conservative call.

scripts/ count: 35 → 28. -1,226 lines of dead code this commit.
Across the three cleanup commits (b6df91a, 1a16e5d, this one):
90 → 28 scripts, -5,672 lines.

tsc clean, 425/425 tests pass.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-04-26 09:51:06 +02:00
g-butandClaude Sonnet 4.6 3aeffe1177 fix(lint): resolve all ESLint errors in scripts/
- eslint.config.mjs: add scripts/** override to allow `any` types
  (one-off migration scripts manipulate JSONB blobs where exact types aren't needed)
- Remove unused imports: computeFitScore, classifyType, existsSync, GROQ_MODELS
- Rename unused vars to _prefix: priority, llmScore, fitDisplay, _i

npm run lint now passes cleanly (0 errors, 0 warnings)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-24 14:23:21 +02:00
g-butandClaude Opus 4.6 17047b1c69 feat: research agent — intelligent contact enrichment pipeline
New 4-phase research agent that works like a human researcher:

Phase 1 DISCOVER: Find foundation in Spheriq directory + web search
Phase 2 VERIFY: LLM judges whether candidate website belongs to foundation
Phase 3 EXTRACT: Pull contacts from verified pages (regex, not guessing)
Phase 4 RECONCILE: Compare sources, pick best, tag provenance

Key design decisions:
- Never guesses URLs or emails — searches and reads actual pages
- LLM used for judgment ("is this the right site?") not extraction
- Outputs ResearchDraft JSON files for human review, NOT direct DB writes
- Records provenance (source + confidence) on every field
- Degrades gracefully without search API (Spheriq-only mode)

New library modules:
- directory-fetcher.ts: Spheriq profile extraction
- web-search.ts: Brave/Google search abstraction (needs API key)
- website-verifier.ts: LLM-based website ownership check
- source-reconciler.ts: Multi-source contact reconciliation

Requires BRAVE_API_KEY or GOOGLE_API_KEY+GOOGLE_CX for full functionality.
Without search API, only Spheriq slug-match discovery works.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-04-09 12:19:47 +02:00
g-but f105bf103f fix: tighten theme classifier and LLM prompt to reduce false-positive fitScores
- Stricter compound rules for digitale-bildung, arbeitsintegration
- Removed overly broad innovation+sozial → soziale-integration rule
- LLM triage prompt now has explicit negative examples (medicine, sports, culture)
- Added rescore-phase2.ts script for batch re-scoring
- Phase2 research data for 2026-03-28 (325 foundations screened)
2026-03-28 19:36:10 +01:00
g-butandClaude Opus 4.6 1454364b12 feat(pipeline): improve graduate script with model selection and incremental saves
Adds --model=8b|70b flag, exports GROQ_MODELS, saves results every 25 entries
to avoid data loss, distinguishes TPD vs TPM rate limits with retry logic,
uses Math.max(algo, llm) for fitScore, upgrades research_depth on enrichment.

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
2026-03-23 11:20:56 +01:00
g-butandClaude Opus 4.6 fa2fad7948 refactor: SSOT cleanup — remove jugend ThemeId, consolidate formatting and config
- Remove `jugend` from ThemeId enum and all 8+ consumers (schemas, metadata,
  fit-scoring, stories, schwerpunkte, theme-classifier, CSS, seed rules, scripts)
- Add THEME_HIERARCHY to schwerpunkte.ts as SSOT for core vs secondary themes
- Consolidate PRIORITY_CONFIG with display colors (textColor, cardColor)
- Extract QUALITY_THRESHOLDS to fit-scoring.ts config
- Replace all .toLocaleString('de-CH') with formatNumber/formatCHF/formatPercent
  from shared format utility (14 files cleaned)
- Extract slug generation to shared src/lib/utils/slug.ts
- Extract PATCH merge logic to src/lib/domain/foundation-config-patch.ts
- Derive PILLAR_BORDER_COLORS from SCHWERPUNKTE.borderClass (config over code)
- Add file size/type validation to foundation bulk import API
- Fix config/documents.ts: use hasGesuchPage instead of heavy domain import
- Remove duplicate local formatCHF functions from 2 components

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-16 14:20:41 +01:00
g-butandClaude Opus 4.6 64d77fd427 refactor: codebase audit fixes — shared components, dedup, accessibility, security
Quick wins (8):
- Add overflow-x-auto to BudgetSection tables for mobile
- Add sr-only text and aria-label for fit stars accessibility
- Add role="dialog" and aria-modal to FilterDrawer
- Add loading state for pipeline slugs fetch
- Add loading fallback for GesuchPageClient (was blank)
- Standardize focus-visible styles, 44px touch targets
- Move hardcoded contact name to ORG_PROFILE
- Delete 11 unused exports across config/domain files

Medium effort (7):
- Extract FieldRow from GesuchEditPanel (445→260 lines)
- Create shared LoadingState + ErrorAlert components, replace 9 inline patterns
- Dedup ResearchDepth type+function across 4 scripts → scripts/lib/utilities.ts
- Dedup slugify across 4 scripts → scripts/lib/utilities.ts
- Add .catch() to 7 async script main() calls
- Make GesuchEditPanel header responsive (mobile stacking)
- Add focus trapping + focus restore to Modal component

Security (from bug hunt):
- Constant-time comparison in middleware, share tokens, cron routes
- Fix error.message leak in one-pager API
- Fix rescore.ts overwriting existing priority values
- Fix applications API missing input validation

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-11 20:41:43 +01:00
g-butandClaude Opus 4.6 e30ed8525b refactor: archive 10 dead scripts, extract shared sleep() utility
Archive superseded ESA screening scripts (v1-v5), phase-3 research,
and other dead scripts to scripts/archive/ (3,710 lines).
Extract sleep() from auto-research + batch-customize to lib/utilities.
Exclude archive/ from tsconfig type checking.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 19:00:10 +01:00
g-butandClaude Opus 4.6 c5ca1fbf35 feat: add research pipeline scripts (triage, auto-research, gesuch-audit, batch-customize)
Five scripts for LLM-assisted batch foundation research via Groq:
- triage.ts: surfaces top research targets from DB
- auto-research.ts: LLM-enriches rapid foundations in batch
- gesuch-audit.ts: quality-checks all foundation Gesuch pages
- batch-customize.ts: generates tailored bridge paragraphs
- lib/groq-client.ts: shared Groq API client

Also: sync filter update, foundation-upsert org_id, audit report refresh.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-06 18:20:47 +01:00
g-butandClaude Opus 4.6 aa33abeaa1 feat: add url-discover + web-enrich enrichment pipeline
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-05 02:34:14 +01:00
g-butandClaude Opus 4.6 7124e7ef0f feat(enrichment): quality tier system + bulk enrichment pipeline + filter redesign
Implements the Systematic Foundation Data Enrichment Strategy:

Layer 1 — Automated bulk enrichment:
- scripts/bulk-enrich.ts: Cross-source enrichment from ESA register + Fundraiso
  discovery. Backfills address (2,291), officialPurpose (37), type classification
  (6), and region (4). Promotes 306 foundations from erfasst → profiliert.
- scripts/foundation-research-queue-v2.ts: Enhanced EV scoring with theme overlap,
  geo bonus, funder/operator classification. Produces priority-ordered research
  queue of top 500 candidates (down from 14,467 unresearched).

Quality tier system (5-tier, computed from data signals):
- verzeichnet → erfasst → profiliert → recherchiert → anwendungsbereit
- QualityTier Zod enum in foundation.ts (SSOT)
- getQualityTier(), tierAtLeast(), getTierPromotionSteps() in foundation-helpers.ts
- Tier labels, colors, descriptions as config constants
- generateFoundationParams() pre-renders profiliert+ only (lower tiers dynamic)

Filter redesign:
- New FilterSidebar + FilterDrawer (mobile) + CollapsibleSection components
- Replaced onlyResearched boolean with minTier quality tier selector
- Schwerpunkte grid, theme checkboxes, boolean toggles, tier distribution
- URL param: ?tier=erfasst (backward compat: ?researched=0 → verzeichnet)

UI tier awareness:
- FoundationCard: tier badge replaces researchDepth badges
- FoundationSidebar: tier card with promotion steps (what's missing)
- FoundationDetailTabs: tier banners, hide Fit/Strategy tabs for low tiers
- Dashboard/Hub: honest tiered metrics (not inflated totals)
- CSS: :where(a) for zero-specificity base link styles

Data: 472 foundations enriched in DB, 15,519 total, 1,274 profiliert+.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-27 00:17:54 +01:00
g-butandClaude Opus 4.6 690e92d76e feat(pipeline): theme classifier extraction + pipeline scripts + 5688 foundations
- Extract shared theme-classifier.ts from batch-research.ts (DRY)
- Add pipeline-incremental.ts for one-command ESA → DB ingestion
- Add esa-bulk-ingest.ts, rescore.ts, zhaw-ingest.ts scripts
- Sync foundations from DB: 5,688 entries via JSON.parse approach
- Add research/drafts/ to .gitignore (too large for git)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-24 12:06:58 +01:00
g-butandClaude Opus 4.6 32c087677f feat(foundations): expand database from 119 → 419 foundations
- Create esa-screen-v3.ts: broader ESA screening combining v2 precision
  exclusions with full screening's theme breadth (1,650 candidates from
  5,392 register entries)
- Create batch-research.ts: mechanical draft generation from ESA purpose
  text with theme classification, type/fit scoring, and quality gate
- Fix foundation-upsert.ts: compute needsResearch dynamically from
  quality gate instead of hardcoding false
- Update research-types.ts: allow _meta passthrough for batch drafts
- Process 300 candidates (waves 1+2), upsert to DB, sync generated file

300 new entries marked needsResearch: true (need website/contact
enrichment). 119 existing entries unchanged at full quality.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-20 12:45:49 +01:00
g-butandClaude Opus 4.6 8f8e9aa057 feat(registry): universal foundation registry with 2-layer architecture
Split monolithic foundationSchema into registrySchema (universal facts) +
analysisSchema (per-org assessment), composed back into identical Foundation
type — zero breaking changes across 56+ consumer files.

- New DB table fundraising_foundation_registry (Layer 1, 5716 entries)
- Added orgId column to fundraising_foundations for multi-org support
- Registry imports: ESA (5392), Fundraiso (126), ZHAW (184)
- ZHAW PDF parsed: 188 ZH social-sector foundations with purpose/deadlines
- Fixed screening pipeline: non-ESA foundations pass as tier 3/4 instead of exclusion
- Scripts: registry-import.ts, zhaw-parse.ts, migrate-registry.ts, foundation-upsert.ts

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-18 21:45:07 +01:00