168 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 Fable 5.2 7ef4611d44 feat(workspace): one sign-in, many organisations; private unless published (#217)
* feat(access): tools and data routes are for members of the organisation

Until now /fundraising and every data route under /api sat behind one shared
HTTP Basic password in the middleware, or behind nothing with
INTERNAL_AUTH=off. No handler asked who was calling, and the organisation
came from the Host header, so the password opened every organisation's data.

- requireOrgPage in one layout covers every tool page; requireOrgApi is the
  first statement of every data handler (28 handlers, and the PDF factory).
  The organisation is the one whose site the request is on, and the caller
  must be a signed-in member of it: 401 signed out, 403 for a member of
  another organisation.
- The shared register of funders is changed only by the platform operator
  (users.role, scripts/set-operator.ts). A member writes its own
  organisation's assessment; a register fact in the same request is refused
  whole, so no edit is half saved.
- Writes and the model route are rate-limited per person with
  @bitbaum/limitkit.
- The activity log records who did it, not 'api'.
- The password gate, the public mode and their helpers are removed; the
  middleware only routes hosts.
- A test reads every route file and refuses a data route without the gate.

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

* wip(access): the workspace URL names the organisation; the gate reads it from there

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

* wip(workspace): tools and data routes move under /o/<slug>; organisations are private unless published

Work in progress on a draft branch: the route and link move is not finished
and the full verify has not been run on this commit.

- docs/PRODUCT.md: the product decision (person, organisations, funders)
- org_profiles.visibility (migration 0021), private by default; revamp-it
  private, its data kept; share links and the workspace still resolve
- scripts/set-visibility.ts

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

* feat(workspace): one sign-in, many organisations; private unless published; the owner is never locked out

The tools and every data route now live in the workspace, /o/<slug>/…, on
the platform's host. The organisation is the one named in the URL and the
caller must be a signed-in member of it. An organisation's own host serves
its public pages only; old links to /fundraising/… there are sent to the
workspace.

Organisations are private unless published (org_profiles.visibility,
migration 0021). revamp-it becomes private: every row is kept, its public
pages stop being served, its share links and workspace still resolve.

The server names its owner in HIRNLI_OWNER_EMAIL. Signed in with that
address verified, they become the operator and the owner of every
organisation that has no member; never a member of one that has members.

Verified: pnpm run verify (1183 tests, build), fleet docs-truth,
composition and experience audits, and a local walk signed out, as an
unverified and as a verified owner address.

Known gap: links from tool pages to an organisation's public pages
(/wirkung, /finanzen, …) do not exist on the platform host yet.

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

* feat(access): the first admin by the fleet's rule: a role from accountkit and a mailed one-hour link

The owner bootstrap matched the signed-in account's address against a
server setting. The fleet's back-office rule (written the same day) says
access is a role on the account, never an address, and the fallback for the
first admin is one button that mails a signed one-hour link to the owner
mailbox. A sign-in through OrangeCat also carries an address OrangeCat made
up, so the match could never have worked for it.

- The operator is now accountkit's admin role.
- The account page offers the button while the account is not an admin and
  the server names a mailbox (OWNER_EMAILS, as in Heidi) and can send mail.
- The link works only for the signed-in account it names, for an hour. It
  makes that account admin and owner of every organisation without a
  member; never a member of one that has members.

Walked locally: signed out, expired, another account's link, the real one.
Not walked: the mail itself (no mail key here).

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 21:06:57 +01:00
CatoandClaude 1dedc4dcb5 feat(auth): every way in on Hirnli's sign-in, and account mail on (#175)
Hirnli's own AuthForm offered email and password only, and the runtime was
created with mail hard-coded off, so there was no sign-in link and no way
back from a forgotten password.

- /anmelden and /registrieren render AccountKit's shared screens in Hirnli's
  look (src/components/auth/AccountScreens.tsx): passkey, email + password,
  the sign-in link, "Passwort vergessen?", "Weiter mit OrangeCat"
  (ORANGECAT_OAUTH_*) and the shared sign-in (SIGNIN_*). Each option shows
  only when its env is set. The browser client carries AccountKit's plugins.
- New /konto: AccountKit's account panel (passkeys, second factor, linked
  sign-ins, sign-out, deletion), linked from the platform nav.
- Account mail goes through createAuthMailer (mail-kit, the fleet key), with
  German subjects. Mail was off because "every existing account is
  unverified": with the AccountKit of the time, mail on made confirmation
  compulsory. Since 0.19 confirmation comes after sign-in, so nobody is
  locked out. An unconfirmed account sees AccountKit's resend on /konto, and
  recovery confirms the address too.
- The journey first asserts every way in the env switches on. CI sets
  synthetic OIDC clients, so both buttons are checked. It then signs up
  through the shared form and checks that /konto offers passkeys and the
  second factor.
- The custom AuthForm and the shared-signin helper are gone; "konto" is a
  reserved slug.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 21:33:09 +01:00
CatoandClaude f1b641075c feat(auth): Abmelden button in the platform nav and the organisation header (#172)
Hirnli moved onto AccountKit's runtime but offered no way to sign out. A
signed-in person now sees "Abmelden" in both chromes that have one: the
platform nav (/start, /organisation-erstellen, …) and the organisation
header under /o/<slug>. The tenant site has no signed-in state, so it has
no button.

- lib/auth/actions.ts: a server action over AccountKit's api.signOut; the
  runtime's nextCookies plugin clears the cookie, the session row is
  deleted, then it lands on /anmelden.
- components/auth/SignOutButton.tsx: one control on the shared Button,
  labels from messages (de/en/fr).
- scripts/auth-journey.mjs: the account job now signs out with the button
  in both places, waits for the network to settle, reloads, and checks the
  session is gone, no session cookie is left and /start sends the person
  to sign in (the prefetch race kivvi #201 found).


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 18:57:08 +01:00
CatoandClaude 117fc53575 fix(deps): take xlsx from the SheetJS CDN (0.20.3), as a devDependency (#171)
xlsx 0.18.5 carries two high advisories (prototype pollution,
CVE-2023-30533; ReDoS, CVE-2024-22363). npm has nothing newer; SheetJS
publishes fixed releases only at cdn.sheetjs.com. Pin the vendor's
0.20.3 tarball (the latest in cdn.sheetjs.com/xlsx.lst), integrity
recorded in pnpm-lock.yaml.

Only scripts/esa-download-and-parse.ts uses it, an offline import, so
it moves to devDependencies and out of the production tree.

pnpm audit: 2 high -> 0 high.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-01 18:54:17 +01:00
CatoandClaude Opus 5.5 ee84d0d767 feat(auth): sign-in runs on @bitbaum/accountkit, with the organization plugin beside it (#151)
* feat(auth): one password rule from accountkit (non-empty, up to 128); drop the 12-character minimum and hint

* chore(deps): accountkit 0.9.1; exemption by name

* feat(auth): sign-in runs on @bitbaum/accountkit, with the organization plugin beside it

Hirnli built its own Better Auth instance. It now uses AccountKit's runtime,
so the sign-in methods, password rule, hashing, limits and cookie rules are
the fleet's, and Hirnli adds what is its own: its tables, its workspaces
(the organization plugin) and its hosts. Tenant hosts are rows in
org_domains and pass the origin check through a lookup, so a customer added
today can sign in today.

Existing people keep their passwords (same scrypt format) and their
sessions (the cookie prefix stays better-auth). Migration 0018 adds the
role and second-factor columns and the passkey and two-factor tables,
additively. Account mail stays off: every existing account is unverified,
and mail on would make verification compulsory.

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

* chore(deps): accountkit ^0.14.0 (plugins and trusted origins)

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

* ci: Hirnli's account journey in a real browser (browser-smoke.yml)

The fleet rollout gate needs a successful browser-smoke.yml on a commit
that changes a shared package. The shared journey does not fit Hirnli
(account mail is off on purpose, people work in organisations), so
scripts/auth-journey.mjs drives Hirnli's own pages against a production
build: sign up, sign out, a wrong password refused, sign in, create an
organisation and open it, a role in the sign-up body ignored, a tenant
host from org_domains accepted and a foreign origin refused (403), and
no sideways scroll at 320/390/1280 with screenshots kept.

The empty CI database takes its schema from the Drizzle definitions:
the committed migration chain does not replay from zero.

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

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-29 12:02:24 +01:00
Cato 4af198ec15 docs(agents): the agent notes live in AGENTS.md; CLAUDE.md is the pointer (#149)
The org rules block sync had added a stub AGENTS.md next to a full CLAUDE.md, leaving two agent files. The content of CLAUDE.md moves to AGENTS.md (with the org rules block under the title), CLAUDE.md becomes the two-line pointer, and the references to CLAUDE.md in this repo now name AGENTS.md. No wording of the notes changed.
2026-10-28 03:49:09 +01:00
CatoandClaude 7a56b2c8c5 docs: correct drifted paths and scripts in agent docs (#141)
Org identity and stories moved from config files to per-tenant rows
(org_profiles, org_content); the Gesuch PDF route lives under api/pdf;
sync scripts and the validate-ssot proposal never existed or were deleted.


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

Co-authored-by: Claude <noreply@anthropic.com>
2026-10-19 13:57:20 +02: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 Opus 5 3fc983555c refactor: one definition per concern — PDF routes, Vorlage pages, sleep, and a 2,168-line table out of a logic file (#119)
* chore(lint): forbid console.log in src, where it would be a defect

A quality sweep read this repo as the fleet's worst source of debug noise:
504 console.log calls. Every one of them is in scripts/ — operator CLIs whose
output IS stdout, where a log line is the feature, not noise. src/ has zero,
and the only reason that is true is that nobody has added one yet.

So the ratchet goes where a console call is actually a defect: a server
component logging to a console no operator reads, or a client component
printing a customer's data into their browser. warn and error stay allowed —
a running server is expected to emit those, and apiError() is built on one.

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

* fix(lint): drop unused FILTER_PRESETS import

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

* refactor(scripts): one sleep, not two

research-agent.ts carried its own copy of the two-line sleep that
scripts/lib/utilities.ts already exports. Same behaviour, one definition.

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

* refactor(pdf): one handler behind both gesuch PDF routes

/api/pdf/gesuch/[slug] and its /onepager sibling were the same 56 lines
twice: same lookup, same not-found and not-ready refusals, same override
application, same headers. They differ in three things — which react-pdf
document is rendered, what the download is called, and what the error log
says — so those are now the three arguments to createGesuchPdfRoute().

The one-pager is the same gesuch, just shorter. With two copies, a fix to
the refusal path could land on one PDF and silently not the other.

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

* refactor(vorlagen): one template page, two ways of labelling it

The two Gesuch-Vorlage routes — [vorlage] and [vorlage]/[type] — rendered
the identical page: VORLAGE banner, hero, the five story sections in one
order, and the two links out. They differ only in wording, because one is
keyed by document type and the other by Schwerpunkt x type. That is now
VorlagePresentation, with the wording as props.

With two copies, a section added to a template appeared on one route and
quietly not the other.

The gesuch.ready check deliberately stays in each route:
every-gesuch-caller-checks-ready.test.ts reads the file that composes a
Gesuch, so hiding the check in a callee would have disarmed the guard.

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

* refactor(vorlagen): one printable Gesuch-Vorlage document

The two dokument routes printed the same thing twice: banner, print bar,
Anschreiben / Projektbeschrieb / Budget / Kurzportrait, back link. What is
printed is what a funder receives, so drift between the copies would mean
two different grant applications leaving the same product.

Now VorlageDokument, with the banner wording and the interaktive link as
props. The dok.ready check stays in the routes for the source-level guard.

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

* refactor(financial): separate four years of bookkeeping from the code that reads it

financial.ts was 2,458 lines, and 2,168 of them were a literal table of
Kivitendo rows for 2022-2025. The other ~290 are the actual module: the
FinanceDataSet queries and the monthly aggregation. Reviewing a change to
the aggregation meant scrolling past four years of accounting.

The table moves to financial-fallback.ts unchanged, byte for byte. This is
not a data table split for line count — it is data leaving a logic file. No
row, no key and no value changed, and the 45 existing tests pass untouched.

Added: AVAILABLE_YEARS is hand-written while the years live in the data, so
a test now pins the list to the table's keys. Import a year and forget the
list and nothing errors — the year simply exists with no picker offering it.

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

* fix(financial): do not add a new tenant-name trace in the moved comment

The no-tenant-traces ratchet counts mentions of the reference tenant's
export file. Rewording the doc comment keeps the budget at 11 rather than
raising it for a sentence.

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

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-15 02:10:07 -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 4dc6a7936f refactor(content): delete the code copy of one customer's story (#102)
`src/lib/config/stories.ts` was 924 lines of one customer's actual narrative —
its WHY sections, competencies, projects, citations, anecdotes, partners and
cover letters. That content moved to `org_content['stories']` weeks ago. The
module stayed as a transitional fallback, so the customer's story existed in two
places at once, which is the SSOT violation this whole migration is against.

The row is the only copy now. Checked against production before merging: it
parses, carries all five themes, all five cover-letter types and six
Kurzportrait rows, and composes.

What kept the module alive was not the product. Only four display strings were
read by anything shipping — `SOCIAL_DISPLAY`, on two gated pages — and they now
live in `config/social-display.ts`, to leave with those pages rather than be
migrated separately. Everything else was tests.

That is the more interesting half. The suite composed its Gesuche from a REAL
customer's prose, so it passed or failed for reasons unrelated to the product,
and one assertion checked that a cover letter contained a particular German word
— true only because the fixture was that customer's content. Tests now use
Lesewerk, an invented organisation, at the same density: five themes, five
letter types, projects with citations, an anecdote, a partner.

Two guards were reframed rather than deleted:

  - the starter block's key list is measured against the SCHEMA now, not
    against the reference customer's block. One customer's content was the
    definition of "complete"; the schema is what every tenant is held to.
  - the ANSCHREIBEN_TEMPLATES and WHY integrity checks asserted the shape of one
    module. They now assert the schema REJECTS a block missing a foundation
    type or a competency slot, and ACCEPTS one whose organisation works in a
    single theme — a stronger guarantee, covering customers this suite has never
    seen.

One guard was deleted with its subject: `stories-block-complete.test.ts` existed
to stop the code block drifting from the stored one. There is no code block.

`no-personal-data-in-numbers` listed the deleted file and failed with ENOENT,
reporting a stale list as a crash. It now names the missing entry instead.

Traces 226 → 199.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 16:21:07 +00:00
CatoandClaude Opus 5 c2a4b9608a feat(account): people can be members of an organisation (#98)
Better Auth's organisation plugin has offered invitations since the day it was
enabled: `org_invitations` in the schema, endpoints live. Nothing ever called
them. So both customers have zero members, nobody can reach either account area,
and the content editor shipped earlier is unreachable by anyone — the third
producer-with-no-consumer found today.

`/o/<slug>/mitglieder` lists members and pending invitations, invites by email,
withdraws invitations and removes members. `/einladung/<id>` is the other end,
public because someone following that link may not have an account yet, and
telling them to ask an administrator when they are holding the administrator's
link is the dead end it removes.

Two departures from the plugin's defaults, both deliberate:

The organisation is named EXPLICITLY on every call. The endpoints fall back to
`session.activeOrganizationId`, and access.ts explains at length why this
product refuses that primitive: one cookie, many tabs, and the acting
organisation changes underneath you. Every function takes a slug and resolves it
through `getOrgAccess`.

No mail is sent and none is pretended. Production has no RESEND_API_KEY, so the
admin gets a link to pass on. "We have emailed them" when nothing left the
building costs someone a day of waiting. The invitation is real either way, and
accepting still requires being signed in as the address it names — Better Auth
enforces that, so it is not re-implemented here.

The two rules that decide who can lock whom out — only an owner grants
ownership, and the last owner cannot be removed — moved into roles.ts as pure
functions with tests. That module is deliberately import-free so questions this
load-bearing are answerable without a DATABASE_URL, and the rules were otherwise
stated inline next to the queries that enforce them.

`scripts/attach-owner.ts` closes the bootstrap gap: an organisation created
before memberships existed has no member who could invite the first one. It
refuses to create the account, because that would mean choosing somebody's
password. The self-serve version — claim by matching email — is unsafe while
`requireEmailVerification` is false, since an address then proves nothing; Kivvi
has the same model, the same lack of verification, and also does this out of
band.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-07 13:57:03 +00: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
CatoandClaude Opus 5 56aca71a71 feat(content): a Gesuch is composed from the applicant's story, not from one in scope (#85)
The composers imported one organisation's narrative and filled the caller's
name into it. A second customer generating a grant application therefore got
the first customer's WHY sections, competencies, projects, citations, anecdotes
and partners — as a complete, confident document, with their own name on it.
That document goes to a funder.

They now take a `TenantStory`: the applicant's block bound to the applicant.
There is no parameter through which another organisation's story can arrive,
and no import left through which one could be reached. An organisation that has
not written a story gets an empty state naming the one thing missing, rather
than somebody else's prose.

Three leaks the name-based ratchet could not see, because none of them contains
the name:

- Three cover-letter openings described one organisation's business in plain
  German — repairing computers otherwise thrown away, combining environmental
  protection with social integration. Emitted under every applicant's
  letterhead.
- The Kurzportrait printed six of one organisation's KPIs, including a CO2
  saving per laptop, for applicants who refurbish nothing.
- `generateThemeAlignments` returned a field named `revampConnection`, read
  from that organisation's WHY sections, on every tenant's foundation page.

So the new test asserts the property rather than a proxy for it: compose the
same document for two organisations with two stories, and no substantial
sentence may appear in both. A sentence surviving both changes came from
neither, which leaves only the code — and the code does not know who is
applying. Mutation-tested by restoring the hardcoded field list.

`CORE_FACTS.metrics` was a fixed tree of one customer's KPIs that the schema
required of everyone; groups and keys are now the tenant's, exposed to content
as `{{metrics.<group>.<key>}}` so a cited figure cannot drift from its source.
The starter block gained the structure a Gesuch actually reads: `HOW: {}` was
valid under the loose schema and composed `undefined` into a new customer's
first document.

The budget block is still one organisation's three-year financial model, shared
by every applicant. It is excluded by name in the new test, with the reason
written down — deleting that line is the definition of done for that migration.

Production `org_content['stories']` gained KURZPORTRAIT_FACTS before this
merges; the row validates against the tightened schema and is otherwise
byte-identical to the code block.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-06 21:58:30 +00:00
CatoandClaude Opus 5 07b9e0f561 feat(parties): foundations become parties, not rows in someone's research (#84)
The model had one kind of account: an organisation seeking funding. Foundations
existed only as 16,623 rows of researched public data that customers formed
opinions about. But a foundation is a party too — it has a purpose, focus areas,
deadlines and an application process, all of which it knows better than anyone
researching it from outside, and its people will have logins.

  organizations.kind          'seeker' looks for funding, 'funder' gives it.
                              Everything that existed was a seeker, hence the
                              default — the code that assumed "organisation
                              means fundraiser" was not wrong so much as
                              unfinished.
  organizations.foundation_id which register entry a funder speaks for. Unique
                              among non-nulls: two accounts must not both claim
                              one foundation, because a Gesuch is addressed to
                              one of them.
  funder_profiles             what a foundation says about ITSELF.

Three layers now sit on the register, and keeping them straight is the design.
The register is the platform's research, shared by all and owned by none. An
ASSESSMENT is what one seeker thinks of a foundation — private, and none of the
foundation's business. A FUNDER PROFILE is the foundation's own account, and it
wins where the two disagree about something the foundation is the authority on.

The overlay is deliberately not a blanket spread. It writes only the fields a
foundation genuinely knows — purpose, contact, deadline wording, grant range,
themes, website. Not fit score, not priority, not Schmuki type: those are the
applicant's or the platform's, and a foundation editing them would be marking
its own homework. A test derives the changed-field set from an actual overlay
and asserts it equals the declared list, so the documentation cannot drift.

RESEARCHED IS NOT STATED. A row is the platform's best understanding until
`confirmed_at` is set; only then is it shown as the foundation's word. This is
the same rule as the seeker side, in the other direction — putting one
customer's certifications in another's deck asserted credentials nobody held,
and presenting our research as a foundation's statement would put words in the
mouth of an organisation that never agreed to them. The detail page says which
it is showing.

A funder has no `org_profiles` row and no host, so `/o/[slug]` branches on kind
rather than sharing a page that half-works: reading a seeker's profile for a
funder account would have thrown.

`scripts/seed-funder-profiles.ts` derives a DRAFT for every register entry, so
foundations find their page filled in and have something to correct rather than
a blank form. Every draft is unconfirmed, which is the whole safety of it —
unconfirmed rows change nothing anyone sees, and it never overwrites a row a
foundation has touched.

Migration 0017 was applied to production before this merges: the access query
selects the new columns, so code landing first would break every signed-in page.
Both existing accounts read back as seekers.

docs/PARTIES.md states the model, including an honest list of what is still
seeker-shaped.


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

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-05 17:27:24 +00:00
67c0da22b2 refactor(tenant): delete the two constants that made one customer compile-time (#81)
ORG_PROFILE and SHARED_ORG_NUMBERS are gone — 82 of the remaining traces, and
the two that made a single customer part of the platform's build rather than
its data.

ORG_PROFILE held that customer's name, both addresses, phone number, contact
person and emails, and four modules still imported it for a founding year, a
programme start and a headcount. Those modules ARE that organisation's dataset
and are gated to it, so the facts now sit in them as their own values, on their
way to `org_content` with everything else. The file is deleted, and with it the
ratchet that existed only to count its importers.

SHARED_ORG_NUMBERS was worse: nine operational figures generated into a
checked-in file from a table in ANOTHER of that customer's databases, imported
by six modules. Two of them are the ones that reach outsiders.

  - opengraph-image.tsx printed that customer's CO2 saving and reuse rate
    beside the READER's founding year, on the card WhatsApp, Slack and LinkedIn
    show when anyone shares a link — a composite claim untrue of either
    organisation. Its header said "no hardcoded stats" directly above them. It
    now shows only what the tenant itself has stated, and a tenant that has
    written less gets a shorter card.
  - ai-presets.ts told every tenant's AI rewrite to work "150 Geräte, 285 kg
    CO2, 75% Reuse-Rate" into its grant text. A preset is an instruction; the
    model already receives the requesting tenant's own context, so it now asks
    for that and explicitly forbids invented or foreign values.

The generated file and its sync script are deleted, along with the npm script
that regenerated them from the other database.

/revamp-2030 becomes /vision. The route put one customer's project name in the
product's URL space, and its nav label said so in three locales. The old path
stays as a permanent redirect, because the address has been linked and indexed
and is not ours to break — the same argument the tenant registry already makes
for keeping a tenant's hostname.

The ratchet caught one of my own mistakes: the bulk rename ran over all of
src/, including the ratchet's own budget table, which ended up with two keys
called `vision`. Cleared spellings now leave the budget list and are asserted
absent instead, so the list stays a work plan rather than a wall of zeroes.

Traces: ORG_PROFILE 45→0, SHARED_ORG_NUMBERS 37→0, revamp-2030 13→0,
revamp2030 4→0, Revamp-IT 103→101, revamp-it 23→18, revampit 20→13,
revamp-info 4→2. 342 → 227.


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 14:48:04 +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
12f651c905 fix(pdf): one tenant's certifications were claimed in another's funder deck (#74)
Generated the pitch deck as the SECOND tenant against production and read the
PDF back as text. It contained, under that tenant's name:

    Warum <reference tenant>?                       (slide 7 title)
    Datenvernichtung nach NIST 800-88 Standard
    SWICO-zertifizierter Partner
    Bestehende Partnerschaften (AOZ, Caritas, RAV, SWICO)

The first line is one organisation's name in another's deck. The rest are
worse. They are CREDENTIAL CLAIMS — a data-destruction standard, a Swiss
recycling certification, three named social-partner relationships — asserted
on behalf of an organisation that holds none of them, in a document written to
be sent to funders. A leak on a web page shows the wrong content; a leak here
makes a false statement of credentials in somebody's funding application.

So the fix is not to substitute the name harder. It is to refuse.
`lib/pdf/authored.ts` gates both funder documents on whether the requesting
tenant actually authored the content they are built from; anyone else gets a
404 saying so. A blank deck and a borrowed deck are both wrong, and the honest
answer is that this tenant has not written one.

Underneath it, the general mechanism. Content had no owner: a module exported
`ANNUAL_PL` and any page rendered it for any tenant, because nothing ever asked
whose figures those were. `lib/content/page-content.ts` gives code-held content
an owner and makes reading it require being that owner. That is deliberately
not "move all content to the database first" — that is weeks of authoring and
fixes nothing until the last line lands. Naming the owner fixes every page at
once, and the eventual DB read is the same call with a different backend.

`CODE_OWNED` is a ratchet of the twelve pages still in that state. It shrinks
as content moves to `org_content`; it may not grow. A page removed from it
stops being served from code entirely, which is asserted — otherwise a
"migrated" page whose reader still falls through would look migrated and behave
exactly as before.

Also adds the reader that never existed. `org_content` has been seeded since
July and `docs/TENANT-MIGRATION-MAP.md` referred to `requireOrgContent`
throwing "by design" — there is no such function, and no reader at all. The
seed wrote into a mirror nobody looked at. `lib/content/org-content.ts` reads
it, validates against a Zod schema at the boundary, and returns null rather
than another tenant's row.

Three literals fixed while here: the slide title, the reference tenant's
deployment slug in every tenant's PDF `creator` metadata (both documents), and
a hardcoded name inside an otherwise-templated indicator sentence in
stories.ts. Guarded by a scanner over lib/pdf that pins itself against a
planted name — with zero offenders left, "nothing matched" is otherwise true
whether the grep works or not.


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 12:28:03 +00:00
896b254123 fix(sources): the CO2 citation in every Gesuch was a 404 (#70)
`CO2_SAVED_PER_LAPTOP` — 285 kg, the most-used number in the impact story and
in the Gesuch — cited Fraunhofer IZM's "Umwelt- und Energiemanagement"
department page. That page 404s. The institute renamed the department to
"Environmental & Reliability Engineering"; same department, same subject
(environmental assessment and life-cycle analysis for electronics), so the
citation stands and only its address had gone stale. Repointed and checked.

A foundation clicking a source link and getting a 404 argues against the number
it is attached to. This is the same failure as the eleven local documents, one
layer out: nothing looks at these links, so nothing noticed when a third party
reorganised their site.

Adds `scripts/check-external-links.sh`, which fetches every complete URL cited
in config and fails on anything that is not 200 (or 403 — weforum.org blocks
bots, and the page is there for a human). URLs built with `${...}` are skipped:
those are search templates, not citations, and cannot be fetched without their
argument.

Deliberately NOT in `verify`. It makes real network calls, so a third party's
outage would turn this repo's CI red for a defect that is not in the commit —
the exact pattern that trains people to bypass the gate. It is a script to run
periodically and whenever a citation changes. Mutation-verified: restoring the
old URL fails it, the new one passes.


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 09:26:38 +00:00
dfea510e77 docs: sync docs with actual stack (#64)
Truth-sweep of README, CLAUDE.md, .claude/CLAUDE.md, docs/**, scripts/README
and org-context docs against actual repo state:

- npm/npx commands -> pnpm/pnpm exec (repo is pnpm@11.25.0)
- Platform name: "undecided, working title Revamp-Info" -> Hirnli (decided,
  PLATFORM_BRAND.name = 'Hirnli')
- Auth: "Clerk or similar / no accounts" -> Better Auth shipped (email+password,
  organisation plugin, /o/<slug>/ routing, registration pages)
- Multi-tenancy: "no runtime multi-tenancy, one repo per org" -> one deployment,
  per-request Host -> tenant resolution (middleware sets x-org-id)
- Foundations table: "13 columns, flat fit_score/priority" -> 9 columns;
  per-org analysis moved to fundraising_foundation_assessments (migration 0015)
- DATABASE_SETUP: "5 tables" -> 16 (9 app + 7 Better-Auth); Node 20+ -> 22.13+
  (.nvmrc 24); broken ./CLAUDE.md relative links -> ../
- DEPLOYMENT: DB is Hirnli's own `hirnli` database (moved 2026-09-02), not the
  shared revampit DB; standard deploy is CD via deploy.yml; migrations are
  auto-applied (additive only) with destructive ones in migrations/manual/;
  stale apps.conf quote; BETTER_AUTH_SECRET/URL env rows; CI = pnpm run verify
- KNOWLEDGE_ARCHITECTURE: stiftungen-generated.ts sync cache (deleted) -> DB
  read layer foundations-repo.ts; removed row for nonexistent
  UX_CONSISTENCY_GUIDE.md
- README: test count 869/40 (and 850) -> 997/56 (measured); "pre-runs sync" and
  "auto-syncs first" removed (no sync step exists); 28 -> 35 page routes;
  23 -> 28 scripts, 18 -> 17 aliases; dead docs/AUDIT_REPORT.md link removed
- ORG-SPECIFIC page paths -> src/app/(tenant)/...; foundation-screen-v3.1.ts
  (nonexistent) -> pnpm run screen; scripts/README gains grant-org-membership
  and seed-org-content rows

Left untouched: HIRNLI-REPLATFORM-PLAN (self-annotated plan), flagged
never-built proposals in KNOWLEDGE_ARCHITECTURE, and the verbatim
`SELF_HOST=1 npm run build` quote of the fleet deploy script.


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-04 16:50:38 +00:00
0bc25d5818 Content becomes template text the tenant fills (#62)
* refactor(content): content becomes template text the tenant fills

The blocker to moving content into org_content was that content already
contained identity. stories.ts interpolated ORG_PROFILE at module load, so the
row seeded from it literally reads "über 23 Jahren Erfahrung" and "seit 2003".
Any second tenant reading that row would send a foundation a Gesuch claiming
the first tenant's founding year — and six of those interpolations were
yearsActive, which is arithmetic on today's date, so the stored copy is right
until 31 December and wrong on 1 January. That is precisely the drift
storedTenantProfileSchema refuses to allow in a profile, arriving through
content instead.

So content is now template text — {{name}}, {{founded}}, {{yearsActive}} —
filled per request from the tenant. The same strings serve every organisation
and the derived ones cannot go stale, because nothing stores them.

CORE_FACTS.organization is gone from the content block entirely. Its name,
legal form, founding year, location, address and website were a second copy of
the tenant's identity; resolveCoreFacts() composes identity from the tenant with
team size from content. TRACK_RECORD.yearsActive was a THIRD copy, recomputed
from that duplicated founding year, and is now tenant.yearsActive.

FILLED IN ONE PLACE, ON PURPOSE

A Gesuch is assembled from a dozen sources, several reached indirectly through
buildStory() and the contextualisation helpers. Filling each at its own call
site makes every future source a chance to forget one, and a forgotten one
ships as "über {{yearsActive}} Jahre" to a foundation. The whole assembled tree
is filled once, at the end of each composer.

That mattered immediately: the first cut leaked ten placeholders through
composeGesuchDokument and the suite stayed green, because every existing
assertion checks a field is truthy or contains a substring, and
"über {{yearsActive}} Jahre" satisfies both. no-unfilled-placeholders.test.ts
asserts the absence directly, across both composers, both readiness branches
and every Schwerpunkt variant.

AND IT CAUGHT A REAL ONE

PARTNER_HIGHLIGHTS carried "seit {{milestones.integrationProgram}}". The second
tenant has no milestones at all, so composing anything — including the public
Gesuch template pages — would have thrown for it. That year is a fact about the
partnership, not about the organisation, so it is content now. A test composes
for a minimal tenant to keep shared content from referencing a fact only one
tenant has.

fillTemplate throws on an unknown placeholder and on a known one the tenant has
not set. Both loud on purpose: the alternative is "gegründet undefined" in a
document somebody posts.

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

* refactor(content): the last client-side content read becomes a prop

GesuchPageClient recomposed the cover-letter opening in the browser to build a
mailto body — the same opening the server had already composed and passed it as
`generatedAnschreiben`. Two derivations of one string from the same inputs,
invisible while both were synchronous and identical.

It stops being invisible once content moves behind a per-request read: a client
component cannot compose from content it has no way to fetch. It now uses the
value it was given.

That was the only place in the client tree that reached into content, so every
content read is now server-side — which is what makes the switch from the
TypeScript literal to org_content a change to one function rather than an async
ripple through the composers.

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 09:26:37 -07:00
fdfa0220ae fix(db): two documented commands that would have destroyed tenant data (#61)
Went looking for the org_content reader migration and found two armed footguns
first. Neither is hypothetical: both are commands this repo tells you to run.

1. `scripts/seed-org-content.ts` would 500 the site.

It upserted ORG_PROFILE straight into org_profiles, and its own header invited
re-running it after any config edit. But org_profiles stopped being a mirror the
moment getTenantById() began reading it on every request — and the row it writes
is one parseTenant() REJECTS. storedTenantProfileSchema is .strict() and
deliberately has no room for yearsActive or experienceLabel, because both are
arithmetic on `founded` and a stored copy goes wrong on 1 January. ORG_PROFILE
carries both. Postgres accepts the row; the next request throws; getTenantById()
throws rather than falling back, on purpose. Every page, 500, from running a
maintenance script exactly as documented.

It no longer writes identity at all — it verifies the row exists and seeds only
content. A tenant's identity is edited in the database; there is no code path
back. Pinned by two tests: that the constant is rejected by the stored-profile
schema, and that no script writes org_profiles.

2. `pnpm db:push` would have offered to delete the seeded content.

drizzle.config.ts points drizzle-kit at schema.ts as the source of truth for the
whole database. org_content and org_scoring — created by migration 0007, holding
this tenant's stories, metrics, cover-letter templates and scoring engines —
were never declared there, so drizzle-kit reports them as unknown and offers to
DROP them. Both are now declared, with a test that fails for any table the
migrations create and do not remove, carrying an annotated exemption list so
adding to it is a decision somebody explains. Mutation-verified.

3. The local test count was other branches'.

Vitest's default include walked into .claude/worktrees/, where concurrent
sessions keep their checkouts. This repo has 53 test files; a run reported 207.
So "green" meant this branch and whatever else happened to be checked out, and
someone else's broken test would fail yours. Excluded, the same way ESLint was
earlier today. True local numbers: 53 files, 972 tests. CI was never affected —
it checks out one branch and no worktrees.

Also verified rather than assumed: all five seeded org_content blocks are
byte-identical to the current TypeScript configs. The July timestamp means the
content has not changed, not that the mirror is stale, so the block-by-block
reader migration can trust the rows.


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 08:01:20 -07: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
ea12e280a1 chore: pnpm — the fleet has one package manager (#54)
- packageManager pnpm@11.25.0; lockfile via pnpm import, package-lock.json gone
- npm overrides moved to pnpm-workspace.yaml overrides (pnpm ignores package.json overrides)
- allowBuilds for @parcel/watcher, @swc/core, esbuild, unrs-resolver (pnpm 11 blocks build scripts otherwise)
- CI: pnpm/action-setup@v6 before setup-node, cache: pnpm, store-dir pinned, pnpm install --frozen-lockfile
- engines: node >=22.13; verify script and sync-numbers converted to pnpm


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-04 09:54:02 +00:00
3c584ea5cd refactor(foundations): give every analysis field exactly one home (#51)
Completes the registry/assessment split. Fit, priority, themes, tagline,
research notes, dates and depth existed in THREE places at once:

  fundraising_foundations.config_data->>'fitScore'   (the blob)
  fundraising_foundations.fit_score                  (a flat column)
  fundraising_foundation_assessments.fit_score       (the real one)

Two of those three are per-organisation values stored on a table every tenant
shares. They cannot be right for more than one customer, and the drift they
invite is not hypothetical — migration 0003 exists because 535 production rows
had a blob and a column disagreeing about the same number. 0015 deletes both
copies that cannot be correct.

The blob copy was more than redundant. The read has to DELETE the blob's
analysis keys before merging, or a tenant with no assessment inherits whatever
the first tenant wrote — Revamp-IT's fit scores and its private research notes,
which say things like "Übereinstimmung mit Revamp-IT-Themen (Fit 2/3)". That
deletion has been load-bearing since #47; after 0015 there is nothing to leak.

Readers moved onto the assessment join, each now stating whose scores it means:

  GET /api/foundations, GET /api/foundations/[id]  — requesting org
  GET /api/applications, /api/applications/[id]    — requesting org
  /api/cron/data-quality                           — reference tenant,
      explicitly, since it has no request to resolve one from and emails
      ORG_PROFILE; tracked with the other ORG_PROFILE consumers
  scripts/audit-pipeline, audit-themes, research-agent — --org

Two bugs fixed along the way, both already on main and both silent:

- applications/[id] built its foundation panel with
  foundationSchema.safeParse(configData). Since the write paths stopped putting
  analysis in the blob, that parse fails for any edited foundation — priority,
  themes, tagline and researchDate are required and absent — so the panel
  rendered empty with no error. It composes from both halves now, like every
  other reader.
- dedupe-by-uid ranked duplicate rows by themes count and research-notes length
  read off the blob. Post-strip both are zero for every row, so the keeper would
  have been chosen on purpose-text length alone. It scores from the assessments,
  aggregated across all organisations — a registry-level decision should not
  turn on who happens to be running the script.

FoundationRowWithAssessment names the shape the UI actually wants — a registry
row with one organisation's rating folded in — so components keep reading
.fitScore while it is explicit that the two halves have different owners.

0015 is guarded and reversible: it refuses to run unless every active row
carrying blob analysis has an assessment row to move it to (verified against
production: 0 orphaned, 16,623 assessments over 15,506 active rows), and copies
the pre-strip blobs to fundraising_foundations_config_pre0015 first. It
deliberately does NOT check that the two copies agree — since the writes moved,
divergence is the correct state, and requiring equality would abort precisely
when the system is working.

MUST BE APPLIED AFTER THIS DEPLOYS. The new code never touches the dropped
columns, but the old code names them explicitly in its SELECTs.


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 18:10:45 -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
2b3f940158 fix(db): make the identity migration re-runnable, and add a membership grant (#38)
The deploy pipeline applies migrations itself, and 0008 was also applied by
hand when Hirnli's database was created. Postgres has no
ADD CONSTRAINT IF NOT EXISTS, so the second application would abort on
"constraint already exists" — and this pipeline aborts the whole deploy on a
failed schema step, shipping no code. Each of the six foreign keys is now
guarded on pg_constraint. Verified by re-running the file against the live
hirnli database: clean, with 2 organisations and 6 constraints unchanged.

Also adds scripts/grant-org-membership.ts. A membership needs a user id, and
the user does not exist until that person registers and picks their own
password — so registration stays theirs and this attaches organisations
afterwards. Idempotent: re-running promotes a changed role and otherwise does
nothing.


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 08:48:42 +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
GandClaude Opus 5 87e10c8434 ci: call the central auto-merge sweep instead of carrying a copy (#9)
auto-merge-sweep.sh was copied into 22 repos and drifted into EIGHT distinct
versions, 245 to 404 lines. Three of them independently grew different fixes for
real outages, and each fix reached only the repo that wrote it:

  evig, revampit   infra-failure detection + re-run. An Actions incident left
                   main "failure" with no failed job at all; 11 PRs stranded
                   for roughly 14 hours.
  fleetcrown       DEADLOCK naming — a red base with the repairing PR sitting in
                   the queue was indistinguishable from "nothing to merge".
  the other 19     neither.

Nothing could carry a fix across, so every repo waited to hit each outage
itself. This repo now calls the canonical sweep in maonakamoto/dotfiles, and the
local copy is deleted.

The canonical is the union of the three, built on the variant ten repos were
already running rather than on the longest one — the 404-line variant is missing
the step-summary reporting the 296-line one has, so "take the biggest file"
would have silently deleted working behaviour. The merge was 106 insertions and
zero deletions: nothing can be lost by adopting it.

The triggers stay in this file because they genuinely are per-repo: workflow_run
must name the CI workflow exactly, and that name differs across the fleet.

Two details that are silent when wrong, both found by piloting rather than
reasoning:

  rearm_workflows is SPACE-separated. The sweep word-splits it; a comma makes
  one bogus token, every dispatch fails, and the only symptom is that nothing
  deploys — while the sweep still exits 0 and reports a successful merge.

  permissions are declared on the CALLER as well. A called workflow's token is
  capped by what the caller grants, so relying on the callee's block alone can
  hand it a read-only token; the sweep would then merge nothing while exiting 0,
  which is indistinguishable from having nothing to merge.

Verified before this rollout: the canonical ran end to end in dotfiles' own CI,
and the reusable-workflow path ran end to end in the pilot repo (s-ink).

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-16 14:54:39 +00:00
G 6fb947e56e fix(ci): declare the failing-job list before the branch that can skip it (#8) 2026-08-07 10:01:28 +00:00
G e53d2f24a3 fix(ci): a red base must not trap the PR that repairs it (#7) 2026-08-07 09:39:31 +00:00
G bb6ff0ea3e fix(ci): stop skipping conflicts, and keep branches current (#6) 2026-08-07 07:16:17 +00:00
GandClaude Opus 5 b5a0858a11 fix(ci): drain the merge queue oldest-first, not newest-first (#5)
`gh pr list` returns newest-first, and the sweep merges the first eligible PR
then stops. So the newest green PR wins every sweep, and an older one can wait
indefinitely.

Observed in maonakamoto/fleetcrown on 2026-08-06: two consecutive sweeps merged
the two newest PRs while three older green ones sat untouched and were never
even evaluated. With several agent sessions opening PRs continuously that is
starvation — and it starves the worst candidate, since the longest-waiting PR
is the one whose checks were proven against the most now-stale base.

PR numbers increase monotonically with creation, so sorting ascending is FIFO.
The ordering was never a decision, just whatever gh happened to return.

Fixed upstream first (fleetcrown #182) and verified in production there: the
sweep immediately after it landed correctly took the oldest open PR rather than
the newest. This is that one-line change, applied to the fleet.

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-06 13:40:27 +00:00
G 9cba336439 ci: green PRs merge and deploy themselves (#4)
* ci: add the auto-merge sweep policy

* ci: green PRs merge and deploy themselves

* ci: allow deploy to be dispatched so an automated merge still ships
2026-08-05 19:16:49 +02: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 cc8b51dc89 feat(ux): pipeline tiles are filters, real pagination, fit-score breakdown
Stiftungen list:
- Every pipeline-overview number is now clickable and filters to exactly the
  rows it counts: P1–P4 tiles toggle the priority filter (aria-pressed ring),
  'Mit Gesuch' toggles a new requireGesuch filter (new URL param gesuch=1,
  removable pill), 'Bewerbungsbereit' applies its preset
- Real pagination (25/page, numbered with ellipsis, mobile: position + arrows,
  44px targets) replaces the endless 'Mehr anzeigen' list; page resets on
  filter change and scrolls to the results anchor

Foundation detail — the '9/10 unclear' fix:
- explainFitScore() in the fit-scoring domain reconstructs the per-dimension
  breakdown: thematic + access recomputed exactly from foundation data,
  geographic derived arithmetically and validated against the dimension max
- FitAnalysis renders per-dimension bars with real numbers (e.g. 4/4 + 3/3 +
  2/3 = 10/10) when the reconstruction reconciles (156/240 P1–P3 today);
  otherwise an honest 'scored from registry data at ingest' note — never
  invented numbers
- Known data drift: scores stored before the current engine config don't
  reconcile; a rescoring batch would fix all 240 but reshuffles P-tiers —
  needs explicit sign-off (documented)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-17 10:50:18 +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
Mao NakamotoandClaude Fable 5 b6b85c9dba security: fail closed in prod without INTERNAL_PASSWORD; move headers/redirects out of dead vercel.json
The Hetzner box ran for a month with no INTERNAL_PASSWORD set, exposing
/fundraising/** and all internal APIs publicly — the middleware's fail-open
default was designed for local dev but applied in production too. Production
now returns 503 on protected routes until the password is configured.

vercel.json headers/redirects/crons did nothing since the self-host migration:
headers+redirects now live in next.config.ts; crons already run as systemd
timers on the box (appcron-revamp-info-*).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 14:42:03 +02:00
g-butandClaude Sonnet 4.6 37bb7ac055 feat(scripts): add --model flag to auto-research.ts for rate-limit fallback
Allows specifying --model=llama-3.1-8b-instant when 70b daily token limit
is exhausted (100k TPD). 8b has 500k TPD with 6k TPM so needs --delay=40000.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-16 08:45:31 +02:00