This file is a merged representation of a subset of the codebase, containing files not matching ignore patterns, combined into a single document by Repomix.
The content has been processed where comments have been removed, empty lines have been removed, content has been compressed (code blocks are separated by ⋮---- delimiter).

<file_summary>
This section contains a summary of this file.

<purpose>
This file contains a packed representation of a subset of the repository's contents that is considered the most important context.
It is designed to be easily consumable by AI systems for analysis, code review,
or other automated processes.
</purpose>

<file_format>
The content is organized as follows:
1. This summary section
2. Repository information
3. Directory structure
4. Repository files (if enabled)
5. Multiple file entries, each consisting of:
  - File path as an attribute
  - Full contents of the file
</file_format>

<usage_guidelines>
- This file should be treated as read-only. Any changes should be made to the
  original repository files, not this packed version.
- When processing this file, use the file path to distinguish
  between different files in the repository.
- Be aware that this file may contain sensitive information. Handle it with
  the same level of security as you would the original repository.
</usage_guidelines>

<notes>
- Some files may have been excluded based on .gitignore rules and Repomix's configuration
- Binary files are not included in this packed representation. Please refer to the Repository Structure section for a complete list of file paths, including binary files
- Files matching these patterns are excluded: **/.git/**, **/.github/**, **/node_modules/**, **/vendor/**, **/third_party/**, **/external/**, **/libs/**, **/lib/**, **/bin/**, **/obj/**, **/build/**, **/dist/**, **/target/**, **/out/**, **/release/**, **/debug/**, **/wwwroot/**, **/public/**, **/assets/**, **/static/**, **/[tT]est/**, **/[tT]ests/**, **/__tests__/**, **/[lL]ogs/**, **/[mM]igrations/**, **/.vs/**, **/.vscode/**, **/.idea/**, **/.pnpm-store/**, **/.yarn/**, **/.npm/**, **/__pycache__/**, **/.pytest_cache/**, **/.mypy_cache/**, **/.gradle/**, **/.mvn/**, **/coverage/**, **/.coverage/**, **/reports/**, **/report/**, **/TestResults/**, **/tmp/**, **/temp/**, **/.tmp/**, **/.cache/**, **/.history/**, **/.DS_Store, **/Thumbs.db, **/*.log, **/*.out, **/*.err, **/*.trace, **/*.trc, **/*.tmp, **/*.cache, **/*.dmp, **/*.dump, **/*.core, **/*.binlog, **/*.ndjson, **/*.jsonl, **/*.csv, **/*.evtx, **/*.etl, **/*.access, **/*.error, **/*.exe, **/*.dll, **/*.so, **/*.dylib, **/*.bin, **/*.app, **/*.msi, **/*.apk, **/*.ipa, **/*.lib, **/*.a, **/*.o, **/*.obj, **/*.lo, **/*.lai, **/*.class, **/*.jar, **/*.war, **/*.ear, **/*.pdb, **/*.idb, **/*.ilk, **/*.nupkg, **/*.snupkg, **/*.gem, **/*.whl, **/*.egg, **/*.deb, **/*.rpm, **/*.zip, **/*.tar, **/*.gz, **/*.tgz, **/*.rar, **/*.bz2, **/*.xz, **/*.7z, **/*.lz, **/*.lzma, **/*.min.js, **/*.min.css, **/*.map, **/*.css, **/*.scss, **/*.sass, **/*.less, **/*.jpg, **/*.jpeg, **/*.png, **/*.gif, **/*.bmp, **/*.tif, **/*.tiff, **/*.webp, **/*.heif, **/*.heic, **/*.svg, **/*.eps, **/*.ai, **/*.raw, **/*.cr2, **/*.cr3, **/*.nef, **/*.arw, **/*.dng, **/*.orf, **/*.rw2, **/*.avif, **/*.apng, **/*.ico, **/*.psd, **/*.psb, **/*.xcf, **/*.hdr, **/*.exr, **/*.dcm, **/*.dicom, **/*.fits, **/*.ppm, **/*.pgm, **/*.pbm, **/*.j2k, **/*.jp2, **/*.pcx, **/*.tga, **/*.iff, **/*.sgi, **/*.ras, **/*.coverage, **/*.lcov, **/*.gcov, **/*.gcda, **/*.gcno, **/*.generated, **/*.g.cs, **/*.designer.cs, **/*.lock, **/*.lock.json, **/*.eot, **/*.ttf, **/*.woff, **/*.woff2, **/*.pfx, **/*.p12, **/*.cer, **/*.crt, **/*.key, **/*.editorconfig, **/*.tool-versions, **/*.onnx, **/*.pt, **/*.pth, **/*.h5, **/*.ckpt, **/*.sln, **/*.csproj, **/*.config, **/*.user, **/*.vsidx, **/*.v2, **/*.db*, **/.*ignore, **/.git*, **/*.config.*, **/*.csproj, **/*.sln, **/*.props, **/.editorconfig, **/.gitattributes, **/.gitignore, **/*.key, **/*.lic, **/docs/openapi/**, **/bin/**, **/obj/**, **/packages/**
- Files matching patterns in .gitignore are excluded
- Files matching default ignore patterns are excluded
- Code comments have been removed from supported file types
- Empty lines have been removed from all files
- Content has been compressed - code blocks are separated by ⋮---- delimiter
- Files are sorted by Git change count (files with more changes are at the bottom)
</notes>

</file_summary>

<directory_structure>
docs/
  Admin.md
  API.md
  Provisioning-Environments.md
  Runbook.md
src/
  KnowledgeFabric.AiGateway/
    Admin/
      AdminAllowance.cs
      AdminAudit.cs
      AdminBody.cs
      AdminEndpoints.cs
      AdminOptions.cs
      AdminPolicy.cs
      AdminServiceCollectionExtensions.cs
      AdminStatus.cs
      AdminUsage.cs
      InstallationQuery.cs
      UsageQuery.cs
    Data/
      DailyUsage.cs
      DatabaseMigrator.cs
      DatabaseOptions.cs
      DataServiceCollectionExtensions.cs
      DesignTimeGatewayDbContextFactory.cs
      EnrolmentAttempt.cs
      GatewayDbContext.cs
      GlobalSpend.cs
      Installation.cs
      Policy.cs
      PolicyStore.cs
    Enrolment/
      AppVersions.cs
      ClientAddress.cs
      Credential.cs
      EnrolmentEndpoints.cs
      EnrolmentVelocity.cs
      InstallationAuthentication.cs
    Forwarding/
      ChatForwarder.cs
      ChatScrub.cs
      ForwardingEndpoints.cs
      ForwardingOptions.cs
      ForwardingServiceCollectionExtensions.cs
      IChatAdapter.cs
      ModelAlias.cs
      OllamaChatAdapter.cs
      TokenLedger.cs
    Licensing/
      LicenceEvaluation.cs
      LicenceExpiry.cs
      LicenceLimits.cs
      StandardLicenceEvaluator.cs
      TrustedLicenceKeys.cs
    Properties/
      launchSettings.json
    Quota/
      AdmissionFilter.cs
      BudgetWindow.cs
      GlobalBrake.cs
      InstallationRateLimiter.cs
      QuotaContext.cs
      QuotaHeaderMiddleware.cs
      QuotaHeaders.cs
      QuotaServiceCollectionExtensions.cs
      QuotaSnapshot.cs
      RequestAllowance.cs
      RequestWindow.cs
      RequestWindows.cs
    Telemetry/
      HealthCheckNoiseProcessor.cs
      SpanTags.cs
      SpendReport.cs
      TelemetryServiceCollectionExtensions.cs
    Usage/
      UsageFlush.cs
      UsageServiceCollectionExtensions.cs
      UsageTally.cs
    appsettings.Development.json
    appsettings.json
    Contracts.cs
    GatewayErrors.cs
    Program.cs
  KnowledgeFabric.AiGateway.Stub/
    Properties/
      launchSettings.json
    appsettings.json
    Contracts.cs
    ControlEndpoints.cs
    OllamaEndpoints.cs
    Program.cs
    StubCredential.cs
    StubErrors.cs
    StubFilters.cs
    StubLicences.cs
    StubOptions.cs
    StubState.cs
    V1Endpoints.cs
CLAUDE.md
docker-compose.postgres.yml
README.md
VERSION
</directory_structure>

<files>
This section contains the contents of the repository's files.

<file path="docs/Admin.md">
# The operator surface — `/admin`

Read the service's status, list installations, read one, revoke one, restore one, read and
change policy, and read what each installation used, day by day. It exists for the question an
operator asks first — is the gateway alright, and what is it spending — for the question a customer
on the phone asks — what am I allowed, and what have I used — for the questions asked a month
later — what did they use last month, and is it growing — for the day an installation has to be
shut off or a lever pulled, and for the questions asked immediately afterwards.

**It is not part of the contract.** [`API.md`](API.md), [`openapi/gateway-v1.yaml`](openapi/gateway-v1.yaml)
and the stub are what a Knowledge Fabric installation builds against, and no installation calls
any of this. Publishing it there would put a surface in the contract that no client has — the
same reason the stub's `/stub/*` switches are absent from the real gateway. It lives here
instead.

What fires when something goes wrong, and which of these levers to reach for when it does, is
[`Runbook.md`](Runbook.md).

It was going to be a CLI. G3 puts the service on an App Service with SCM basic authentication
disabled, so there is nowhere comfortable to run one, and the choice collapsed to endpoints
([#4](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/4)).

---

## The tokens

Two bearer tokens, each an application setting set in the Portal alongside the connection string
and the provider key
([#40](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/40)):

| Setting | Accepted on | Give it to |
|---|---|---|
| `Admin__Token` | Every method: the reads, revoke, restore, the policy writes, and any write this surface gains later | An operator who acts on installations or policy, and a client once it writes |
| `Admin__ReadToken` | `GET` and `HEAD` only: the status, the list, one installation, the policy, the tiers and the usage history | A client that only reads. Optional |

**Give a client that only reads the read token.** kf-admin's console is one: its read-only pages
ship first, behind a shared password until per-person sign-in
([kf-admin#15](https://github.com/KnowledgeFabric/kf-admin/issues/15)), and whoever gets past that
password should get a dashboard, not a revoke button. It holds the read token as its
`Gateway--AdminToken` until its writes ship
([kf-admin#63](https://github.com/KnowledgeFabric/kf-admin/issues/63)).

Both are **configuration, not policy**: policy lives in the database, the database is backed up
for thirty-five days, and a token in the database is a credential in thirty-five days of copies.

```bash
# What to paste into the Portal, once for each setting. Generate each, do not invent either.
openssl rand -base64 32
```

Saving an application setting restarts the app, which drops any chat streaming at the time.

- **No `Admin__Token`, no admin surface.** The endpoints are not mapped, so they answer `404`
  like anything else this service does not serve, **whatever `Admin__ReadToken` says**: the read
  token alone maps nothing, and the gateway logs a warning saying so at startup. That is the safe
  failure: a misconfigured environment has no operator surface rather than an open one.
- **No `Admin__ReadToken`, one token.** `Admin__Token` is then the only token accepted, as before
  #40.
- **Either token shorter than 32 characters fails the process at startup**, with a message naming
  the setting. These are credentials a person chooses rather than a generator, and both open the
  list.
- **A read token equal to `Admin__Token` fails the process at startup.** Two names for one
  credential is worse than one name: a client handed "the read token" would hold a revoke button
  while everyone believed otherwise.
- **The read token on anything but `GET` or `HEAD` is a bare `403`**: it authenticated, and it is
  not allowed. The request does nothing, so the installation or row it named is untouched. The rule
  is by method rather than by route, which is how the policy writes
  ([#39](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/39)) were closed to the read token
  without anyone having to remember them.
- **A token that is neither is a bare `401`**, on every method. This surface has no
  `X-KF-Error-Code` vocabulary, and nothing to tell a caller who does not already hold a token.

---

## The endpoints

```bash
ADMIN=https://ai.knowledgefabric.io
TOKEN=…            # the Admin__Token value. Every GET accepts Admin__ReadToken as well.
OPERATOR=…         # you, as the audit line should name you. See "Every write leaves a line".

# What is deployed, the brake, the fleet's counts and the caller's address. See "The status".
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/status"

# Newest installations first; limit defaults to 100 and is capped at 500. The total the filter
# matches is in the X-Total-Count header. See "Filters, order and paging".
curl -s -i -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/installations?limit=20"

# The next page of the same list.
curl -s -i -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/installations?limit=20&offset=20"

# Filters combine: active Enterprise installations seen this month, biggest spenders first.
curl -s -H "Authorization: Bearer $TOKEN" \
  "$ADMIN/admin/installations?row=enterprise&status=active&seen_since=2026-09-01T00:00:00Z&sort=tokens_used"

# What the minimum-version lever would refuse if it were set to 1.7.0.
curl -s -i -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/installations?app_version_below=1.7.0"

# One installation, or 404.
curl -s -H "Authorization: Bearer $TOKEN" \
  "$ADMIN/admin/installations/3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11"

# Every installation holding one licence, revoked or not, however old. limit does not apply.
curl -s -H "Authorization: Bearer $TOKEN" \
  "$ADMIN/admin/installations?licence_id=00000005-0000-4000-8000-000000000001"

# Every installation on a licence that more than one active installation holds. limit applies.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/installations?shared=true&limit=500"

# Withdraw access. Every subsequent call from this installation is refused 403
# installation_revoked — including one made with a credential it re-enrols for afterwards.
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
  "$ADMIN/admin/installations/3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11/revoke"

# Give it back.
curl -s -X POST -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
  "$ADMIN/admin/installations/3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11/restore"

# The policy rows, read and changed. See "Policy".
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/policy"
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/tiers"

# The fleet's use, day by day and split by row; then one installation's. See "Usage history".
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/usage/daily?from=2026-09-01&to=2026-09-30"
curl -s -H "Authorization: Bearer $TOKEN" \
  "$ADMIN/admin/usage/daily?from=2026-09-01&to=2026-09-30&installation_id=3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11"

# A range's totals, by row, and the ten biggest spenders in it.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/usage/summary?from=2026-09-01&to=2026-09-30"
```

Each returns the installation as the operator sees it — id, application version, tier, status,
created, last seen, revoked, the licence's id and how many installations hold it, the licence
state the application is told, and what it is allowed and has used (see *An installation's
allowance*). **Never the credential hash**: it identifies the installation to anyone who holds it,
and no question an operator asks needs it.

Revoking twice keeps the first instant. The second was not the decision. Each revoke and restore
leaves an audit line naming who asked: see *Every write leaves a line*.

An unknown installation id is `404`, on the read as on revoke and restore. A revoked installation that re-enrols gets a `201` and a
fresh credential — enrolment is unauthenticated and tells a caller nothing — and every call made
with that credential is still refused `403`. Revocation is not something a caller launders by
asking again.

### An installation's allowance

Every installation `/admin` returns carries `allowance`: what it is allowed and what it has used
([#38](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/38)). kf-admin's installations
page and its usage-by-licence page read it
([kf-admin#65](https://github.com/KnowledgeFabric/kf-admin/issues/65),
[kf-admin#66](https://github.com/KnowledgeFabric/kf-admin/issues/66)), so these names are its
client's: fields are added, never renamed or removed.

```json
"allowance": {
  "row": "standard",
  "requests": { "limit": 120, "remaining": 117, "reset_at": "2026-09-26T15:31:00Z" },
  "tokens":   { "limit": 2000000, "used": 418220, "reset_at": "2026-10-01T00:00:00Z" },
  "max_predict_tokens": 4096,
  "from_licence": { "tokens": 2000000, "period": null, "rpm": null }
}
```

| Field | What it says |
|---|---|
| `row` | The allowance row the installation is served: `evaluation`, `standard` or `enterprise`. Not the wire tier, which calls the last two `licensed`. A licensed installation with no licence tier is `standard`, which is what it is served. |
| `requests` | The request window: `limit` a window, what is `remaining` of it, and `reset_at`, when the window next frees a request. |
| `tokens` | The token budget: `limit` a period, what is `used` in the current period, and `reset_at`, when the period ends. |
| `max_predict_tokens` | The longest reply the gateway lets the provider write, the row's. A licence never sets it. |
| `from_licence` | What the installation's licence set over its row: `tokens` (`ai.tokens`), `period` (`ai.period`, `month` or `30d`) and `rpm` (`ai.rpm`). Each is `null` where the row's number applies, and all three are `null` when the installation is not licensed. |

- **It is the installation's own `GET /v1/installation`, read by the same code.** `requests` and
  `tokens` are exactly the `quota` the installation is told at the same instant, and the numbers
  its `X-KF-*` headers carry. When a customer reads a number off their AI Manager screen, this is
  that number.
- **`from_licence` says whose number it is.** `tokens.limit: 10000000` with `from_licence.tokens:
  null` is the row's budget, and moves with a `PUT` to that row (*Move a tier's allowance*). `tokens.limit: 2000000` with
  `from_licence.tokens: 2000000` is the licence's, and only a new licence moves it. `0` is a
  limit the licence carried that could not be read, which allows nothing (see *What a licence sets
  over its row*).
- **`requests.remaining` is this process's count, and a restart resets it.** The request window
  lives in the gateway's memory, which is why production runs one instance: after a deploy, a
  setting saved in the Portal or a crash, every installation reads full again, here and in its own
  `X-KF-Requests-Remaining`. `started_at` on `GET /admin/status` says when that last happened. The
  token budget is in the database, and a restart does not touch it.
- **`tokens.used` is the current period only.** A counter left from a period that has ended reads
  `0`, as it does on the wire. Earlier periods are in *Usage history*.
- **A revoked installation reports what it would be served if restored.** Its `status` is what says
  it is served nothing.
- **Changing a row is reported on the next read.** The rows are read once for each request, however
  many installations it returns, and never kept between requests.

### Filters, order and paging

`GET /admin/installations` takes these, all optional, and they combine: an installation is listed
when it matches every filter given.

| Parameter | Lists |
|---|---|
| `licence_id=<guid>` | Installations holding that licence id, revoked or not and however old. See *One licence on more than one installation*. |
| `shared=true` | Installations whose licence id more than one active installation holds. |
| `row=evaluation\|standard\|enterprise` | Installations served that row, as `allowance.row` reports it. |
| `status=active\|revoked` | Installations not revoked, or revoked. |
| `seen_since=<instant>` | Installations whose `last_seen_at` is at or after the instant. Write it in UTC with a `Z`, `2026-09-01T00:00:00Z`: a `+` in a query string arrives as a space, so an offset has to be sent as `%2B02:00`. |
| `app_version_below=<version>` | Installations whose `app_version` the minimum-version lever would refuse `426 app_version_unsupported` if it were set to this. It reads versions exactly as the lever does, so the list is what setting it would cost: a prerelease counts as its release, `1.7` is below `1.7.0`, and a stored version that does not read as one is below everything. See *Retire an application generation*. |

| Parameter | Does |
|---|---|
| `sort=created\|last_seen\|tokens_used` | Orders newest first by `created_at` (the default) or by `last_seen_at`, or largest first by `allowance.tokens.used`. Ties go to the newer installation, then by id, so the order is the same on every page. |
| `limit=<n>` | Returns at most `n`. Defaults to 100; below 1 is 1 and above 500 is 500. It does not apply with `licence_id`, whose installations are always returned whole. |
| `offset=<n>` | Skips the first `n` of the order. Defaults to 0. |

- **The body is a bare list, and the total is a header.** `X-Total-Count` is how many installations
  the filters match, before `limit` and `offset`, and it is the same on every page. Walk a list by
  adding the number of rows each page returned to `offset` until a page comes back empty, or until
  `offset` reaches `X-Total-Count`. A page past the end is `[]`, not an error.
- **`sort=tokens_used` orders by the current period's spend, as the rows report it**, and so reads
  every installation the filters match to put them in order. At this fleet's size that is one
  small query. The other orders are the database's.
- **Anything the list cannot answer is `400`, never ignored.** The body names the parameter:

  ```json
  { "error": "invalid_parameter", "parameter": "row", "message": "row must be one of evaluation, standard, enterprise." }
  ```

  `invalid_parameter` is a parameter this gateway has, given a value it cannot read or given more
  than once. `unknown_parameter` is a parameter it does not have, which to a client usually means a
  gateway older than the filter it sent. A gateway before #35 ignores `licence_id=` and answers
  with the unfiltered list, which is why kf-admin checks each row against what it asked for; from
  this one on, a filter this gateway does not have is refused instead, so a filtered answer can be
  trusted as one. Parameter names ignore case.
- **Only the list takes these.** One installation by id takes none, and neither do revoke and
  restore.

### The status

`GET /admin/status` answers "is it alright, and what is it spending" in one body
([#37](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/37)). kf-admin's gateway overview
reads it ([kf-admin#64](https://github.com/KnowledgeFabric/kf-admin/issues/64)), so these names are
its client's: fields are added, never renamed or removed.

```json
{
  "version": "0.1.0+85ec7e4713ea65fc36d3e8375f2379f02b711340",
  "started_at": "2026-09-26T08:00:00Z",
  "now": "2026-09-26T15:30:00Z",
  "telemetry": { "configured": true },
  "brake": {
    "ceiling": 50000000,
    "used": 1234567,
    "period_start": "2026-09-01T00:00:00Z",
    "period_end": "2026-10-01T00:00:00Z",
    "tripped": false
  },
  "spend": {
    "day": "2026-09-26",
    "tokens_today": 72000,
    "tokens_trailing_daily_mean": 21500,
    "trailing_days": 7
  },
  "installations": {
    "total": 42, "active": 40, "revoked": 2,
    "by_row": { "evaluation": 30, "standard": 9, "enterprise": 1 },
    "seen_last_24h": 12, "seen_last_7d": 25, "seen_last_30d": 38,
    "licensed_without_licence_tier": 3
  },
  "caller": { "address": "203.0.113.7" }
}
```

| Field | What it says |
|---|---|
| `version` | `VERSION`, then `+` and the commit the deployed package was built from. After a deploy, it should be `develop`'s head. |
| `started_at` | When this process started. A restart nobody announced — a setting saved in the Portal, a platform move, a crash — shows here. |
| `now` | The instant the counts and the brake were read at. |
| `telemetry.configured` | Whether `APPLICATIONINSIGHTS_CONNECTION_STRING` was set when the process started. `false` on the deployed service means Application Insights is hearing nothing from it. |
| `brake` | The global brake, read by the same code admission reads it with: `tripped: true` means the next chat is `503 service_paused`. `ceiling` is `null` when the brake is off. `used` is what the whole service has spent between `period_start` and `period_end`, the calendar month. See *Release the global brake*. |
| `spend` | Today against the week before ([#50](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/50)): the reading the spend report logs every quarter hour and the *Spend anomaly* alert compares ([`Runbook.md`](Runbook.md)), read by the same code but current to this request. `day` is the UTC day `tokens_today` counts, so far. `tokens_trailing_daily_mean` is the `trailing_days` whole days before it, divided by that many, with a day nobody chatted counting as zero. There is no ratio: the mean is zero until the fleet has a week behind it. |
| `installations.total`, `active`, `revoked` | Every installation, as `/admin/installations` lists them. |
| `installations.by_row` | Active installations by the allowance row each is served: `evaluation`, `standard` or `enterprise`. They add up to `active`. This is not the wire tier, which calls the last two `licensed`. |
| `installations.seen_last_24h`, `seen_last_7d`, `seen_last_30d` | Active installations whose `last_seen_at` falls in each window. |
| `installations.licensed_without_licence_tier` | Active licensed installations with no licence tier, served `standard` whatever their licence says. See *Raise a licence tier's allowance*. |
| `caller.address` | The address the gateway attributes to this request, read exactly as an enrolment's is. It is not stored and not logged. See *Arm the enrolment velocity limit*. |

- **Everything after `revoked` counts active installations only.** A revoked installation is
  served nothing, whatever its row says, and a revoked one that keeps calling is still refused.
- **The rows are counted as the list reports them.** A licence whose expiry has passed is lapsed
  the next time its installation calls. Until then the list shows it `licensed`, and `by_row`
  counts it on its licence's row. From that call on, both say `evaluation`.
- **Nothing in it names the upstream**, the model behind the alias, a token or a prompt. The
  upstream is not called to produce it either: a status that probed the provider would spend
  money on every page view. Upstream health is the 5xx rate
  [#8](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/8) alerts on.
- **A database that cannot be read is `503` with `{ "error": "database_unreachable" }`**, answered
  within three seconds, so a client with a five-second timeout, the console's, hears it rather
  than timing out. `/health` stays `200` meanwhile, on purpose: this endpoint is where a database
  outage is allowed to show. The gateway logs a warning with the reason.
- **The read token is enough.** It is a `GET`.

### One licence on more than one installation

**A licence covers one installation** (kf-admin `docs/License-Contract.md`, *One licence, one
installation*,
[kf-admin#47](https://github.com/KnowledgeFabric/kf-admin/issues/47)). A customer with three
installations has three licences, and so does Knowledge Fabric. kf-app checks a licence offline and
never sees another installation, so the gateway is the only place one licence on two installations
can be noticed ([#35](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/35)).

**The gateway watches for it and never enforces it.** Both installations enrol `licensed` and are
served exactly as either would be alone. Nothing is refused or downgraded for it: deciding is the
operator's, and the lever is the revoke above. Enforcing would have left a reinstalled customer on
`evaluation`, because a reinstall enrols under a new installation id, until someone released the
old one.

Each row carries two fields for this:

- **`licence_id`**: the `Id` of the licence the installation was accepted with, or `null` when it
  holds none. It is recorded only from a licence that verified: a file that does not verify can
  claim any id, and recording it would make someone else's licence look shared. `Quantity` is not
  read. It is always `1`, and the contract forbids reading it as a count of installations or seats.
- **`licence_holders`**: how many installations that **have not been revoked** hold that id,
  counting this row unless it is revoked itself. It is `null` when there is no id. Above `1` means
  the licence is shared.

When the id changes:

- **Written** on every accepted licence, at enrolment and by `PUT /v1/installation/licence`.
- **Kept** by a re-enrolment without a licence, which is the application recovering its
  credential. It is the same row, so it never counts as a second installation.
- **Kept** by a renewal. A renewal keeps its licence's id
  ([kf-admin#42](https://github.com/KnowledgeFabric/kf-admin/issues/42)) and replaces the file on
  the same installation, so the count does not move.
- **Cleared** when the licence is removed (`{ "licence": null }`) and when it lapses. A lapse is
  noticed the next time that installation calls, so one that never calls again keeps counting
  until it is revoked.
- **Never set** on installations licensed before #35 deployed. The licence is not kept, so there
  is nothing to read the id back from. Such an installation has no id until kf-app sends its
  licence again ([kf-app#968](https://github.com/KnowledgeFabric/kf-app/issues/968)); until then
  it counts nowhere, and a licence it shares can look held alone.

The two filters, which combine with each other and with the rest of *Filters, order and paging*:

- **`licence_id=<guid>`** returns every installation holding that id, revoked ones included and
  however old. `limit` does not apply, because a licence's installations are asked about whole.
  `offset` does, so a client paging through any list reaches an empty page. An id nobody holds
  returns `[]`, and one that is not a GUID is `400`.
- **`shared=true`** returns every row whose id has a `licence_holders` above `1`. Revoked rows
  holding the id are included, so for each shared id it lists what `licence_id` would. It never
  returns a row without an id. `limit` and `offset` apply, as to the plain list.

kf-admin's console reads both, with `GET` alone, so the read token is enough for it
([kf-admin#58](https://github.com/KnowledgeFabric/kf-admin/issues/58)). The parameter names and
`licence_id` on the row are what it depends on, so a change to either is a change to kf-admin too.

#### What to do about a shared licence

1. **Find the installations.** `shared=true` lists them. Put them side by side with
   `licence_id=<guid>`, and compare `created_at` and `last_seen_at`. A reinstall looks like an old
   installation that stopped calling and a new one that started soon after it.
2. **Ask the customer first.** A reinstall, a restored backup, or a test box built from a
   production image are all honest ways to get here. The customer knows which installation should
   hold the licence, and whether the other still runs.
3. **Revoke the installation that should not have it**, with the revoke above. It stops counting
   at once, and the licence is no longer shared. An abandoned installation loses nothing by it. A
   running one is refused `403 installation_revoked` from its next call, and stays refused if it
   re-enrols.

If the customer needs a second installation, the answer is a second licence, issued in kf-admin.
A revoked installation cannot install anything, so restore it first, then have the customer
install the new licence there. It counts as sharing the old licence until they do.

### Usage history

`allowance` and the status say what is being spent now. Neither says what was spent before:
`TokensUsed` is the current budget period and `GlobalSpend` the current month, and each forgets
its figure when its period rolls. The daily usage ledger keeps it
([#41](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/41)). kf-admin's usage history
reads it ([kf-admin#70](https://github.com/KnowledgeFabric/kf-admin/issues/70)), so these names are
its client's: fields are added, never renamed or removed.

#### The ledger

The `DailyUsage` table holds one row per installation per UTC day, with these counts:

| Column | Counts |
|---|---|
| `Tokens` | What the provider said the day's chats cost, the same figure the token budget is spent from. |
| `Requests` | Every request the installation made on the forwarded surface (`/api/chat`, `/api/show` and `/api/tags`), admitted or refused. `/v1` is not counted: reading the allowance does not spend a request. |
| `RefusalsRateLimited` | Requests refused `429 rate_limited`. |
| `RefusalsBudgetExhausted` | Requests refused `429 token_budget_exhausted`. |
| `UpstreamErrors` | Chats the provider failed: `502 upstream_unavailable`, `504 upstream_timeout`, and an answer that broke off after it began. A client that hung up is not one. |

- **Every count after `Requests` is part of it.** A refused request is still a request, so
  `requests` minus the two refusals is what got past the installation's own limits. A
  `503 service_paused` is a request and none of the three: the brake stops the whole service, and
  `brake` on the status is where that shows.
- **Which day.** Tokens count on the day the chat ended, because that is when they became known: a
  turn that runs past midnight UTC counts on the new day. An upstream error counts when the chat
  ended too. A request and its refusal count on the day the request arrived.
- **When a count arrives.** Tokens are written as each chat ends. That is one more write per chat,
  not per request: an `UPDATE`, and after it an `INSERT` on the installation's first chat of the
  day, when the `UPDATE` found no row. Requests, refusals and upstream errors are counted in the gateway's memory and written every
  **minute**, because request counting was taken out of the database on purpose and this does not
  put it back. So a `429` reaches these reports up to a minute after it was answered.
- **What a restart loses.** A process that shuts down writes what it has not written yet before it
  exits: a deploy, a setting saved in the Portal and a platform move lose nothing. A process that
  dies without shutting down loses up to a minute of requests, refusals and upstream errors, the
  same bound the request window lives with. It never loses tokens. A shutdown that runs out of time
  logs *"Shutdown ran out of time before the daily usage was written"*.
- **A database that will not take the write** keeps the counts in memory and tries again the next
  minute, logging *"The daily usage flush wrote N of M installation-days"* each time it fails. The
  counts wait for the database rather than being lost, unless the process stops meanwhile.
- **Kept indefinitely.** These are counters, and D-D keeps counters indefinitely while request
  metadata goes after 30 days. A fleet of a few hundred installations is about 100,000 rows a year.
  There is no pruning job, and none is needed at that size.
- **Metadata only**: an installation id, a date and five numbers. Nothing a prompt or an answer
  could land in.

From `psql`, one installation's days:

```sql
SELECT "Day", "Tokens", "Requests", "RefusalsRateLimited", "RefusalsBudgetExhausted", "UpstreamErrors"
FROM "DailyUsage" WHERE "InstallationId" = '3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11' ORDER BY "Day";
```

#### The reports

`GET /admin/usage/daily?from=<date>&to=<date>` is every day of the range, oldest first. Without an
installation id, each day is the fleet's, split by row:

```json
[
  { "day": "2026-09-25", "tokens": 5400, "requests": 61, "refusals_rate_limited": 2,
    "refusals_budget_exhausted": 0, "upstream_errors": 1,
    "by_row": {
      "evaluation": { "tokens": 1200, "requests": 20, "refusals_rate_limited": 2, "refusals_budget_exhausted": 0, "upstream_errors": 0 },
      "standard":   { "tokens": 4200, "requests": 41, "refusals_rate_limited": 0, "refusals_budget_exhausted": 0, "upstream_errors": 1 },
      "enterprise": { "tokens": 0, "requests": 0, "refusals_rate_limited": 0, "refusals_budget_exhausted": 0, "upstream_errors": 0 } } },
  { "day": "2026-09-26", "tokens": 0, "requests": 0, "refusals_rate_limited": 0,
    "refusals_budget_exhausted": 0, "upstream_errors": 0, "by_row": { "…": "every row, at zero" } }
]
```

With `&installation_id=<guid>`, each day is that installation's, with the same five counts and no
`by_row`.

`GET /admin/usage/summary?from=<date>&to=<date>` is the range's totals, the same split by row, and
the installations that spent the most in it:

```json
{
  "from": "2026-09-01", "to": "2026-09-30",
  "totals": { "tokens": 1234567, "requests": 4210, "refusals_rate_limited": 12,
              "refusals_budget_exhausted": 3, "upstream_errors": 5, "installations": 38 },
  "by_row": {
    "evaluation": { "tokens": 402000, "requests": 2900, "…": "…", "installations": 29 },
    "standard":   { "tokens": 700000, "requests": 1200, "…": "…", "installations": 8 },
    "enterprise": { "tokens": 132567, "requests": 110,  "…": "…", "installations": 1 }
  },
  "top_installations": [
    { "installation_id": "3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11", "row": "standard", "tokens": 418220,
      "requests": 900, "refusals_rate_limited": 0, "refusals_budget_exhausted": 0, "upstream_errors": 1 }
  ]
}
```

| Parameter | Does |
|---|---|
| `from=<date>`, `to=<date>` | The range, both **required** and both **included**, as UTC dates: `2026-09-01`, with no time. At most **366 days**, so a leap year is one call. Longer is refused, not shortened: ask in parts. |
| `installation_id=<guid>` | Daily only. That installation's days instead of the fleet's. |
| `limit=<n>` | Summary only. How many `top_installations`. Defaults to 10; below 1 is 1 and above 50 is 50. |

- **A day with nothing counted is present, at zero.** Never absent: the daily report has exactly
  one entry per day of the range, every row present in each `by_row`, so a chart has nothing to
  fill in. An installation id with nothing in the ledger is a range of zeros, not a `404`, as a list
  filtered by a licence nobody holds is `[]`.
- **The summary's totals are the sum of the daily report's days** for the same range, and its
  `by_row` adds up to its totals. `installations` is how many installations have a day in the range,
  which is how many made any request in it.
- **Rows are the rows installations are served now.** The ledger keeps counts, not rows, so an
  installation that bought a licence during the range has the whole range under its licence's row,
  and an installation's figures move between rows when it changes row. `row` on a top installation
  is its `allowance.row`.
- **An installation deleted from `psql`** still counts in the totals, since it spent what it spent,
  and in no row. It is listed in `top_installations` with `row: null`. Nothing in the gateway deletes
  an installation, so this only happens by hand.
- **The last minute is not here yet**: see *When a count arrives*. Neither report writes anything or
  waits for the next write.
- **Anything a report cannot answer is `400`, naming the parameter**, as the list does:
  `invalid_parameter` for a missing or unreadable date, a `to` before `from`, a range over 366 days,
  or a parameter given twice; `unknown_parameter` for one the report does not take, the other
  report's included.
- **The read token is enough.** Both are `GET`s.

---

## Policy

The tier allowances, the minimum accepted application version, the enrolment velocity numbers and
the global brake's ceiling are **policy**: they live in the database so they can change without a
deploy. `/admin` reads and writes them
([#39](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/39)). kf-admin's policy page reads
them ([kf-admin#67](https://github.com/KnowledgeFabric/kf-admin/issues/67)) and its edit page writes
them ([kf-admin#71](https://github.com/KnowledgeFabric/kf-admin/issues/71)), so these names are its
client's: fields are added, never renamed or removed.

### The rows

`GET /admin/policy` is the one row of gateway-wide levers:

```json
{ "minimum_app_version": "0.0.0", "enrolments_per_hour": null, "enrolments_per_day": null, "global_token_ceiling": 50000000 }
```

| Field | What it is | What a write takes |
|---|---|---|
| `minimum_app_version` | The oldest application version that may enrol. Below it, `426 app_version_unsupported`. Seeded `0.0.0`, which admits everyone. | A version as enrolment reads one: `1.7` and `1.7.0` do, `latest` and `1` do not. At most 32 characters. |
| `enrolments_per_hour`, `enrolments_per_day` | Enrolments allowed from one address in an hour and in a day. `null` is no limit, which both are seeded to. | `null`, or a whole number, 1 or more. The hourly limit no higher than the daily one when both are set, since the daily one would always refuse first. |
| `global_token_ceiling` | Tokens the whole service may spend in a calendar month before every chat is `503 service_paused`. `null` is no brake, not a brake at zero. | `null`, or a whole number, 1 or more. |

`GET /admin/tiers` is the three allowance rows, in this order:

```json
[
  { "tier": "evaluation", "requests_per_window": 30, "request_window_seconds": 60, "token_budget": 1000000,
    "budget_period": "rolling_30_days", "max_predict_tokens": 4096, "installations_served": 30 },
  { "tier": "standard", "requests_per_window": 120, "request_window_seconds": 60, "token_budget": 10000000,
    "budget_period": "calendar_month", "max_predict_tokens": 4096, "installations_served": 9 },
  { "tier": "enterprise", "requests_per_window": 120, "request_window_seconds": 60, "token_budget": 10000000,
    "budget_period": "calendar_month", "max_predict_tokens": 4096, "installations_served": 1 }
]
```

| Field | What it is | What a write takes |
|---|---|---|
| `tier` | The row: `evaluation`, `standard` or `enterprise`, the word `allowance.row` and `by_row` use. | Nothing: the path names the row. |
| `requests_per_window` | Requests an installation may make in the window. | A whole number, 1 or more. |
| `request_window_seconds` | The window they are counted over, a minute in every row today. | A whole number of seconds, 1 or more. |
| `token_budget` | Tokens an installation may spend in a period. | A whole number, 1 or more. |
| `budget_period` | `rolling_30_days`, thirty days from where the installation's period started, or `calendar_month`, in UTC. | One of those two words, exactly. |
| `max_predict_tokens` | The longest reply the gateway lets the provider write: a larger `num_predict` is clamped to it. | A whole number, 1 or more. |
| `installations_served` | Active installations served this row, counted as `installations.by_row` on the status counts them: whom a change reaches. A revoked installation is served nothing and is not counted. | Nothing: it is counted. |

`standard` and `enterprise` are the two licence tiers' rows. A licensed installation is served the
one its licence's `tier` names: `enterprise` when the licence says exactly that, and `standard` for
anything else (#32). On the wire both are `licensed`, so the headers never say which row an
installation is on; `allowance.row` on the installation does.

There is a fourth row in the table, **`licensed`, which nothing reads.** It is the single row the
two licence tiers replaced, left in place until a later release deletes it, because the version
before #32 read it for every licensed request and could still be running while the migration ran.
It is not listed, and `PUT /admin/tiers/licensed` is `404`: changing it would change nothing.

### Changing a row

A `PUT` writes **the whole row**, every field. Read the row, change what you mean to, and write it
back:

```bash
# The gateway row: here, the minimum version.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/policy" \
  | jq '.minimum_app_version = "1.7.0"' \
  | curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
      -H "Content-Type: application/json" --data-binary @- "$ADMIN/admin/policy"

# A tier: the same, leaving out the two fields the tier reports and a write does not take.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/tiers" \
  | jq '.[] | select(.tier == "evaluation") | del(.tier, .installations_served) | .requests_per_window = 60' \
  | curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
      -H "Content-Type: application/json" --data-binary @- "$ADMIN/admin/tiers/evaluation"
```

- **A missing field is refused, not read as `null`.** On these rows `null` turns a lever off, so a
  client that sent only the field it meant to change would otherwise release the brake by leaving
  it out.
- **The answer is the row as written**, `200`, and a tier's carries its `installations_served`.
- **It is felt on the next request.** Nothing is cached: the rows are read on every request, and the
  request window counts an installation's requests whatever limit they were admitted under. Lowering
  `requests_per_window` refuses an installation that has already made that many on its very next
  request, and raising it releases one sitting at the old limit. Changing `request_window_seconds`
  starts every window on the row empty, as a restart does.
- **A tier other than `evaluation`, `standard` or `enterprise` is `404`**, `licensed` included.
- **The read token is `403`** on both, and nothing is written.
- **Anything the gateway will not write is `400`, naming the field, and the row is left exactly as it
  was.** The body is the list's shape with `field` for `parameter`:

  ```json
  { "error": "invalid_field", "field": "budget_period", "message": "budget_period must be rolling_30_days or calendar_month." }
  ```

  | `error` | Means |
  |---|---|
  | `invalid_body` | The body is not a JSON object. `field` is `null`. |
  | `unknown_field` | A field the row does not have, which to a client usually means a gateway older than the field. It is refused rather than ignored, so nobody believes they moved a lever that is not here. |
  | `invalid_field` | A field the row has, missing, given twice, or given a value the tables above do not allow. `tier` and `installations_served` in a tier's body are refused this way too, with a message saying why. |
  | `invalid_header` | An `X-KF-Operator` the line cannot carry. See *Every write leaves a line*. |

  Field names ignore case. Numbers are JSON numbers: `"5"` and `5.0` are refused.

Two of these rules exist because the same values set by hand fail quietly. A `minimum_app_version`
that does not parse admits everyone, on purpose — a typo must not lock the fleet out — so from
`psql` the lever is simply not pulled and nothing says so. A `budget_period` the gateway does not
know throws on every request for that row. Here there is someone to tell, so both are refused.

### Every write leaves a line

Every revoke, restore, `PUT /admin/policy` and `PUT /admin/tiers/{tier}` logs one event, at
`Information`, under the category `KnowledgeFabric.AiGateway.Admin.AdminAudit`:

```text
Admin tier of evaluation by you@knowledgefabric.io at /admin/tiers/evaluation: {"requests_per_window":30,"request_window_seconds":60,"token_budget":1000000,"budget_period":"rolling_30_days","max_predict_tokens":4096} became {"requests_per_window":60,...}
```

| Property | What it holds |
|---|---|
| `Action` | `revoke`, `restore`, `policy` or `tier`. |
| `Target` | The installation id, the tier, or `gateway` for the policy row. |
| `Operator` | `X-KF-Operator`, or `unnamed`. |
| `Path` | The request's path. |
| `Before`, `After` | The row, or the installation's `status` and `revoked_at`, as JSON in the shape `/admin` reports it. |

- **`X-KF-Operator` names the person acting.** Optional, at most 128 characters, no control
  characters. kf-admin sends its audit actor. Absent or blank, the line says `unnamed`. Longer, given
  twice, or carrying a control character, the write is refused `400 invalid_header` and nothing is
  written: a write whose line could not say who asked is not made. A `GET` ignores it.
- **It is logged and never trusted.** It plays no part in authorisation, which is the token's alone:
  anyone holding the admin token can name anyone. It says which person a shared token was acting
  for, as far as the client holding the token knows.
- **One line per write made**, whatever it changed: a second revoke, or a `PUT` of the values already
  there, is a line. A write refused `400` or `404` changed nothing and leaves none. The line is
  written after the change is saved, so none is left by a write that failed.
- **Metadata only**, as everything the gateway logs is: an installation id, a row's numbers, a
  revocation instant, a path and a name. No token, no address and no body reach it.

On the deployed service the lines are in Application Insights:

```kusto
traces
| where customDimensions.CategoryName == "KnowledgeFabric.AiGateway.Admin.AdminAudit"
| project timestamp, Operator = customDimensions.Operator, Action = customDimensions.Action,
          Target = customDimensions.Target, Before = customDimensions.Before, After = customDimensions.After
| order by timestamp desc
```

With `telemetry.configured: false` on the status, they reach only the App Service log stream.

### Without the console: `psql`

The rows can still be changed with `psql`, for a gateway with no admin surface (no `Admin__Token`)
or none running. [`Provisioning-Environments.md`](Provisioning-Environments.md) has the Cloud Shell
path to a prompt; connect as the database's own login. Each section below gives the `UPDATE` after
the `PUT`. **None of the checks above applies to it and it leaves no line**: a minimum that does not
parse admits everyone, a period the gateway does not know refuses every request on its row, and
nobody is recorded as having done either. Read the row back with `GET` afterwards.

### Retire an application generation

```bash
# Anything below this is refused 426 app_version_unsupported at enrolment.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/policy" \
  | jq '.minimum_app_version = "1.7.0"' \
  | curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
      -H "Content-Type: application/json" --data-binary @- "$ADMIN/admin/policy"
```

```sql
-- From psql. Nothing checks this value: see "Without the console".
UPDATE "GatewayPolicy" SET "MinimumAppVersion" = '1.7.0' WHERE "Id" = 1;
```

Seeded at `0.0.0`, which accepts everything. A minimum that started at the current version would
retire the fleet on the day the gateway shipped. **Ask what it would cost first:**
`GET /admin/installations?app_version_below=1.7.0` lists exactly the installations the change
above would refuse the next time they enrol, and its `X-Total-Count` is how many. Add
`status=active&seen_since=…` to leave out the revoked and the long gone. The `PUT` refuses a value
that does not parse as a version. From `psql`, such a value accepts everything rather than nothing,
so that a typo there does not lock every installation out of the product — check the row after
changing it, because the lever failing quietly is the intended failure, and a quiet lever does
nothing.

### Arm the enrolment velocity limit

Seeded **off**, by the decision on [#4](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/4):
wanting to install the product too many times is a better problem than refusing a legitimate
rollout. While both are `null` nothing is counted and no address is recorded.

```bash
# The scope's original numbers, for the day someone abuses an unauthenticated endpoint. Past them,
# enrolment from that address is 429 enrolment_rate_limited.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/policy" \
  | jq '.enrolments_per_hour = 5 | .enrolments_per_day = 20' \
  | curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
      -H "Content-Type: application/json" --data-binary @- "$ADMIN/admin/policy"
```

```sql
-- From psql. Nothing checks these: 0 fails every enrolment from every address.
UPDATE "GatewayPolicy" SET "EnrolmentsPerHour" = 5, "EnrolmentsPerDay" = 20 WHERE "Id" = 1;
```

Disarm it by writing both back as `null`.

> **Verify the address before arming this.** Behind App Service the connection is from the
> platform's front end, not from the caller, and the gateway reads the entry the front end
> appends to `X-Forwarded-For`. That handling has unit tests but **has never been checked against
> a real App Service response**, because nothing reads it while the limit is off. Armed against
> the wrong address, the limit refuses everybody. Confirm what the platform actually sends first.
>
> `caller.address` on `GET /admin/status` is the address the limit would count, read the same way.
> Call it through `https://ai.knowledgefabric.io` from a machine whose public address you know
> (`curl -s https://ifconfig.me`). The two must be the same address. If `caller.address` is
> anything else — the platform's own front end, a private address, `unknown` — do not arm the
> limit: it would count every installation against that one address.

Counting resumes from empty when the limit is armed: the window fills over the following hour
rather than reaching back over enrolments nobody recorded.

### Move a tier's allowance

```bash
# Evaluation: sixty requests a minute and two million tokens a period.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/tiers" \
  | jq '.[] | select(.tier == "evaluation") | del(.tier, .installations_served)
        | .requests_per_window = 60 | .token_budget = 2000000' \
  | curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
      -H "Content-Type: application/json" --data-binary @- "$ADMIN/admin/tiers/evaluation"
```

```sql
-- From psql. Nothing checks these: see "Without the console".
UPDATE "TierPolicies" SET "RequestsPerWindow" = 60, "TokenBudget" = 2000000 WHERE "Tier" = 'evaluation';
```

The answer's `installations_served` is whom the change reached. From `psql`, `Tier` is
`evaluation`, `standard` or `enterprise`, and `BudgetPeriod` is `rolling_30_days` or
`calendar_month` and nothing else — the gateway refuses to read a value it does not recognise rather
than guessing one, so every request on the row fails until it is put right.

Reported immediately in the quota headers and `GET /v1/installation`, and **enforced** from the
next request: the policy is read per request, and the in-process request window counts an
installation's requests whatever limit they were admitted under, so lowering a limit refuses an
installation already past it and raising one releases an installation sitting at the old one,
without a restart.

To see which row a licensed installation is on and what its licence set over it, the installation
itself says: `allowance.row` and `allowance.from_licence` on `GET /admin/installations/{id}`. From
`psql`:

```sql
SELECT "Id", "LicenceTier", "LicenceTokenBudget", "LicenceBudgetPeriod", "LicenceRequestsPerMinute"
FROM "Installations" WHERE "Tier" = 'licensed';
```

#### Raise a licence tier's allowance

```bash
# Every Enterprise customer, at once, with no licence reissued.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/tiers" \
  | jq '.[] | select(.tier == "enterprise") | del(.tier, .installations_served)
        | .requests_per_window = 600 | .token_budget = 50000000' \
  | curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
      -H "Content-Type: application/json" --data-binary @- "$ADMIN/admin/tiers/enterprise"
```

```sql
-- From psql.
UPDATE "TierPolicies" SET "RequestsPerWindow" = 600, "TokenBudget" = 50000000 WHERE "Tier" = 'enterprise';
```

The two start equal, at the numbers the `licensed` row held, so shipping them moved nobody.
Enterprise's numbers are a commercial decision, and this is how they are applied once made.

- **A licence tier's allowance only goes up** while any licence on that tier is in force (kf-admin
  `docs/License-Entitlements.md`, *The AI allowance per tier*). Raising it reaches every such
  licence at once, which is the point. Lowering it would shrink what customers bought under
  licences that still say the same thing. A plan that needs less is a new tier, or numbers written
  into the licences issued on it.

  **The gateway does not enforce this.** Whether a licence on a tier is in force is a question for
  kf-admin's licence register, and the gateway sees only the licences that enrolled. kf-admin's
  edit page applies the rule
  ([kf-admin#71](https://github.com/KnowledgeFabric/kf-admin/issues/71)); a `PUT` sent by `curl`,
  or an `UPDATE` from `psql`, that lowers `standard` or `enterprise` is accepted, and is the
  operator's to justify. The `PUT`'s audit line records who made it and what the row was before.
- **Installations licensed before #32 have no `LicenceTier`, and are served `standard`**, whatever
  their licence says. The licence is not kept, so it cannot be read again, and such an
  installation stays on `standard` until a licence reaches the gateway again. That costs nothing
  while the rows are equal. Before raising `enterprise`, look for them:
  `installations.licensed_without_licence_tier` on `GET /admin/status` says how many there are,
  and the query above lists them with a `NULL` `LicenceTier`. An Enterprise customer among them has to install their licence again
  from a kf-app that sends it on install
  ([kf-app#968](https://github.com/KnowledgeFabric/kf-app/issues/968)); an older kf-app sends it
  only at first enrolment.
- **A new tier reaches the gateway before any licence carries it.** A tier the gateway does not know
  is served `standard`. The gateway logs *"The licence's tier is not one this gateway knows; the
  standard allowance applies"* when it accepts one, which is how a licence that got there first is
  noticed.

#### What a licence sets over its row

A licence that sets `ai.tokens`, `ai.period` or `ai.rpm` keeps the licence's numbers, and its row
reaches only what the licence leaves out (#28). They are the other three columns the query above
reads, and this is where to look when an installation is served numbers its row does not explain.

`NULL` is the row's number. `0` is a limit the licence carried that could not be read, which
allows nothing: the gateway logs *"The licence's ai.tokens cannot be read, so it allows nothing"*
when it accepts one. Changing a customer's allowance is a new licence, issued in kf-admin and
installed from kf-app, rather than an `UPDATE` to these columns, which `/admin` does not write: the
next licence the installation sends overwrites them, `LicenceTier` included.

### Release the global brake

The gateway stops forwarding for **everybody** with `503 service_paused` once the whole service
has spent `GlobalTokenCeiling` tokens in the current calendar month. It is
[kf-app#817](https://github.com/KnowledgeFabric/kf-app/issues/817)'s interim cap, seeded at
50,000,000 — a placeholder to tune from G8's metrics, and deliberately generous: it is a runaway
detector, not a second rate limit. The provider-side hard cap stays behind it as the backstop.

**Read the state before changing anything.** `brake` on `GET /admin/status` is the brake as
admission reads it, by the same code: whether it is `tripped`, what has been `used` against the
`ceiling`, and the month it is counted over. Read it again after the `PUT`: `tripped` is `false`
on the next read, as the next chat is admitted.

```bash
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/status" | jq .brake

# Let it run again. This is the whole of the recovery.
curl -s -H "Authorization: Bearer $TOKEN" "$ADMIN/admin/policy" \
  | jq '.global_token_ceiling = 100000000' \
  | curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H "X-KF-Operator: $OPERATOR" \
      -H "Content-Type: application/json" --data-binary @- "$ADMIN/admin/policy"

# Or turn the brake off entirely, which leaves only the provider-side cap: the same, with
# '.global_token_ceiling = null'.
```

```sql
-- The same from psql, where the admin surface is not to hand.
SELECT g."TokensUsed", g."PeriodStart", p."GlobalTokenCeiling"
FROM "GlobalSpend" g, "GatewayPolicy" p;

UPDATE "GatewayPolicy" SET "GlobalTokenCeiling" = 100000000 WHERE "Id" = 1;

-- Off. 0 is not off: it is a brake that pauses the service for everyone.
UPDATE "GatewayPolicy" SET "GlobalTokenCeiling" = NULL WHERE "Id" = 1;
```

Two things follow from the brake being **computed from `GlobalSpend` rather than held in memory**,
and both are the point rather than side effects:

- **A restart does not release it.** That is deliberate — a brake that cleared itself on restart
  would resume spending, and a runaway is exactly the thing that gets a process restarted. Raising
  the ceiling is the only way out, and it takes effect on the next request.
- **`GlobalSpend` is state, not policy.** It is the record of what was spent and it is not an
  operator's to edit; the ceiling is the lever, and `/admin` writes the ceiling and never the
  counter. Zeroing the counter from `psql` to release the service would destroy the evidence of the
  incident that tripped it.

`PeriodStart` rolls itself: the first chat of a new month starts the counter again, so a ceiling
raised during an incident does not need lowering back on the first of the month unless the number
itself was wrong.

---

## After a restore

Losing the installations table costs every installation a re-enrolment, not a customer: an
application answered `401 installation_unknown` enrols again by itself. What it does cost is the
usage counters, and — if the velocity limit has been armed by then — a herd of re-enrolments
arriving from the same handful of addresses at once. **Turn the limit off in the restored database
before repointing at it** — the `UPDATE` in *Arm the enrolment velocity limit*, with `NULL` for both
— and back on with a `PUT` once the fleet has settled.

The usage history is in the same database, so a restore takes it back to the same instant: the days
since then are lost with everything else. It is keyed by the installation id the application
generated, which a re-enrolment keeps, so each installation's history lines up again as the fleet
re-enrols.
</file>

<file path="docs/API.md">
# Gateway API — `/v1`

The contract between a Knowledge Fabric installation and the AI Gateway. Both repositories
build against this file: the gateway implements it (kf-ai-gateway G4–G7), the application
consumes it (kf-app A2–A6). It writes down decisions D-A to D-F of the epic
([kf-app#954](https://github.com/KnowledgeFabric/kf-app/issues/954)); the reasoning lives
there and in ADR D21, not here.

Base address `https://ai.knowledgefabric.io`, a compiled constant in the application,
overridable only in Development (D-E).

> The `/v1` prefix is the **gateway's own** versioned surface. It is not Ollama's
> OpenAI-compatible `/v1/chat/completions`, which the gateway does not expose.

An OpenAPI 3.0 document for the `/v1` surface is [`openapi/gateway-v1.yaml`](openapi/gateway-v1.yaml).
A stub that answers this contract in memory ships in the same repository; see
[The stub gateway](#the-stub-gateway).

---

## Two surfaces

| Surface | Paths | Who calls it |
|---|---|---|
| Gateway-native, versioned | `POST /v1/installations`, `GET /v1/installation`, `PUT /v1/installation/licence` | The application's enrolment client (A2) |
| Ollama-native, forwarded | `POST /api/chat`, `POST /api/show`, `GET /api/tags` | The application's existing Ollama connector, unchanged (D-B) |

Plus `GET /health`, which is unversioned, unauthenticated and carries no quota headers: it is
the readiness signal for the platform health check and the deploy, and it answers even when the
provider is down.

Everything else is refused with `404`, and an allow-listed path called with the wrong method
with `405`. Both come from routing before any gateway code runs, so they carry no
`X-KF-Error-Code` and no quota headers — a scanner learns only what this document publishes.
In particular `/api/generate` and `/api/embeddings` are never forwarded: there is no completion
surface and no vector store in the product. Adding a path is a change to this file and to
kf-app, never a route quietly added to `appsettings.json`.

---

## Identity

An installation has no bundled secret. On first use of Knowledge Fabric AI the application
generates a fresh GUID — the *gateway installation id* — enrols it, and stores the credential
the gateway issues (D-A). That GUID is not the one `InstallationIdProvider` holds: that id
salts the usage-data hashes and must never leave the box.

**Credential format.** `kfg_` followed by 32 random bytes in unpadded base64url:

```
kfg_[A-Za-z0-9_-]{43}
```

47 characters in total. The prefix exists so that secret scanning — GitHub's, and anyone
else's — can match the credential on sight. The gateway stores only its SHA-256: the value
in the enrolment response is the only time the credential exists in plaintext outside the
installation, and it appears in no log line, no error body and no metric label.

**Rotation.** Re-enrolling an installation id issues a new credential and invalidates the old
one. The installation's counters survive it, and so does its tier: a re-enrolment carrying no
`licence` leaves the licence and the tier the installation already had. A re-enrolment that does
carry one is evaluated exactly as a first enrolment is, and replaces what was there; removing a
licence is the deliberate act `PUT /v1/installation/licence` with `null` provides.

That asymmetry is there because the application re-enrols **by itself** whenever the gateway
answers `401 installation_unknown`, and that recovery has no reason to be holding the customer's
licence — a paying installation must not drop to `evaluation` as a side effect of an internal
retry. It is also what makes the gateway's installation table non-critical: losing it costs usage
counters, not customers.

Because enrolment is open, an installation id is the only thing needed to rotate that
installation's credential. The id is an unguessable GUID that otherwise never leaves the
installation, and the gateway holds no content, so the exposure is a nuisance the victim
recovers from by re-enrolling — not a disclosure. Enrolment velocity limits per source
address (G4) bound it.

---

## Authentication

Every call except enrolment and `/health` carries the credential as a bearer token:

```
Authorization: Bearer kfg_…
```

| Status | `X-KF-Error-Code` | What the application does |
|---|---|---|
| 401 | `installation_unknown` | Enrol again, then retry once. Missing, malformed and unrecognised credentials are all this. |
| 403 | `installation_revoked` | Stop. Show the suspension sentence; do not retry, do not re-enrol. |

Neither carries quota headers: no installation is identified by a request the gateway refuses
at authentication.

---

## Enrolment

`POST /v1/installations` — unauthenticated.

```json
{
  "installation_id": "3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11",
  "app_version": "1.6.2",
  "licence": "<signed licence XML, or null>"
}
```

The payload is **exactly** these three fields. No hostname, no customer name, no user data, and
no room for any: a body carrying an unknown field is refused with `400 invalid_request` rather
than ignored, so that a field nobody agreed to cannot arrive by accident.

`201 Created`:

```json
{
  "credential": "kfg_ExampleOnlyNotARealCredential00000000000000",
  "tier": "evaluation",
  "licence": { "status": "absent", "reason": null, "expires_at": null }
}
```

`tier` is `licensed` when the licence verifies against any of the Knowledge Fabric public keys
the gateway trusts, and `evaluation` otherwise — including when the licence is expired or forged. **An unverifiable
licence never fails enrolment**: evaluation stays zero-touch, and the `licence` object reports
why the tier is what it is.

| `licence.status` | `licence.reason` | Meaning |
|---|---|---|
| `absent` | `null` | No licence was sent. The bundled trial is unsigned and is this case. |
| `accepted` | `null` | Verified; `expires_at` is the licence's expiry, and the tier is `licensed` until then. |
| `rejected` | `expired` | Verified but past its expiry. |
| `rejected` | `unverifiable` | Not signed by any trusted Knowledge Fabric key, or not a licence the gateway can accept: a trial licence, one whose `validFrom` has not arrived, or one declaring a `schemaVersion` it does not read. `expires_at` is `null`. |

Verification follows the licence contract (KnowledgeFabric/kf-admin `docs/License-Contract.md`),
whose reasons are finer than these two: its `unsupported-schema`, `trial-licence` and
`not-yet-valid` are all reported here as `unverifiable`.

The `201` carries the quota headers, so the application knows its allowance without a second
call. Enrolment refusals:

| Status | `X-KF-Error-Code` | Cause |
|---|---|---|
| 400 | `invalid_request` | Not JSON, a missing or non-GUID `installation_id`, a missing `app_version`, or an unknown field. |
| 426 | `app_version_unsupported` | `app_version` is below the minimum the gateway accepts. The lever that retires an image generation (D-A); the application asks the user to update. |
| 429 | `enrolment_rate_limited` | The source address has enrolled too often. Carries `Retry-After`. |

---

## Self

`GET /v1/installation` — tier and quota for the AI Manager screen. It reads the counters and
**does not spend a request** against the rate limit (D-C).

```json
{
  "installation_id": "3f8a1c2e-9b40-4d7a-9a1e-2b6c5d0f7e11",
  "tier": "evaluation",
  "status": "active",
  "quota": {
    "requests": { "limit": 30,      "remaining": 27,     "reset_at": "2026-09-03T14:31:00Z" },
    "tokens":   { "limit": 1000000, "used":      418220, "reset_at": "2026-10-03T00:00:00Z" }
  },
  "licence": { "status": "absent", "reason": null, "expires_at": null }
}
```

`status` is `active` on every `200`: a revoked installation is refused with `403` here as
everywhere else. The field is in the body so the application binds it once, and so that a
later state — additive, per the versioning rule — needs no new shape.

## Licence

`PUT /v1/installation/licence` — install or renew a licence on an enrolled installation (A6).

```json
{ "licence": "<signed licence XML>" }
```

`200 OK` returns the resulting tier and licence, in the same shapes as above:

```json
{
  "tier": "licensed",
  "licence": { "status": "accepted", "reason": null, "expires_at": "2027-09-01T00:00:00Z" }
}
```

Unlike enrolment, this is a deliberate act with a licence in hand, so a licence that does not
verify is an error rather than a silent downgrade: `422` with `X-KF-Error-Code: licence_rejected`
and `reason` in the body (`expired` or `unverifiable`). The installation keeps the tier it had.

Sending `{ "licence": null }` removes the licence and returns the installation to `evaluation`.

---

## Quota headers

Every response the gateway itself produces or forwards for an identified installation carries
all seven — successes and refusals alike, on both surfaces, including the enrolment `201`:

| Header | Value |
|---|---|
| `X-KF-Requests-Limit` | Requests allowed in the rate window. |
| `X-KF-Requests-Remaining` | Requests left in the current window; never below `0`. |
| `X-KF-Requests-Reset` | RFC 3339 UTC instant the window resets, e.g. `2026-09-03T14:31:00Z`. |
| `X-KF-Tokens-Limit` | Tokens allowed in the budget period. |
| `X-KF-Tokens-Used` | Tokens counted in the current period. |
| `X-KF-Tokens-Reset` | RFC 3339 UTC instant the budget period resets. |
| `X-KF-Tier` | `evaluation` or `licensed`. |

They are absent from `/health`, from routing's `404`/`405`, and from `401`/`403`, where no
installation is identified.

The limits are the installation's own: its tier's, or, for a `licensed` installation, its
licence's tier's row and its licence's own numbers where it sets them
([Tiers and policy](#tiers-and-policy)). `X-KF-Tier` names the tier either way.

Token counts are the provider's own, read from the final `done: true` chunk of a chat
(`prompt_eval_count` + `eval_count`). They are known only once an answer ends, and the headers
are written before it begins, so a chat's own tokens appear in the headers of the **next**
response rather than its own. `GET /v1/installation` reads the counters after the fact, which
is what the AI Manager screen does.

---

## Refusals

Every refusal the gateway generates carries `X-KF-Error-Code` and a JSON body with the same
code:

```json
{
  "code": "token_budget_exhausted",
  "message": "This installation has spent its token budget for the current period.",
  "resets_at": "2026-10-01T00:00:00Z"
}
```

`resets_at` appears only on `token_budget_exhausted`. `message` is a fixed English sentence for
logs and support; the application renders its own copy, in the user's language, from `code`.
Clients read the code, never the sentence.

| Status | `X-KF-Error-Code` | Also | Meaning |
|---|---|---|---|
| 400 | `invalid_request` | | A body the endpoint cannot read: malformed JSON, or a field the enrolment payload does not have. |
| 401 | `installation_unknown` | | Unknown, malformed or missing credential. Enrol again. |
| 403 | `installation_revoked` | | Access withdrawn. Do not retry. |
| 404 | `model_unknown` | | `model` was not the alias. See below. |
| 422 | `licence_rejected` | `reason` | The licence does not verify. `PUT /v1/installation/licence` only. |
| 426 | `app_version_unsupported` | | The application is older than the minimum. Enrolment only. |
| 429 | `enrolment_rate_limited` | `Retry-After` | Too many enrolments from this source address. Enrolment only. |
| 429 | `rate_limited` | `Retry-After` | The installation's request rate limit. |
| 429 | `token_budget_exhausted` | `Retry-After`, `resets_at` | The installation's token budget for the period. |
| 502 | `upstream_unavailable` | | The provider failed. Nothing of the provider's answer reaches the body or the headers (D15). |
| 503 | `service_paused` | `Retry-After` | The global brake tripped. Everyone; alerting fires (G8). |
| 504 | `upstream_timeout` | | The provider did not answer within the gateway's connect, first-byte or total timeout. |

The body shape above is the gateway's on **both** surfaces: a refusal on `/api/chat` is a
gateway error, not an Ollama one, so a client on the forwarded surface must key off
`X-KF-Error-Code` rather than the body's shape.

### Admission

Admission is decided when a request starts. A request that was admitted **completes**, even if
its own tokens carry the installation past its budget mid-stream (D-C); the overage is counted
and the next request is refused. This is what lets a streamed answer never be cut in half.

---

## The forwarded surface

### The model alias

The gateway advertises exactly one model, `knowledge-fabric-ai`, and maps it to whatever it
runs. The application never learns the real model, which is D15 with nothing left to leak.

- `GET /api/tags` lists that one model and nothing else. Its `modified_at`, `size` and `digest`
  are opaque: they describe the alias, not the model behind it.
- `POST /api/chat` requires `model` to be `knowledge-fabric-ai` (a `:latest` suffix is accepted
  and ignored). Any other value is `404 model_unknown` — the gateway is not a way to reach the
  provider's other models. The value is replaced with the real model on the way upstream.
- `POST /api/show` for the alias answers with the real model's **capabilities** and nothing
  else that names it:

  ```json
  {
    "capabilities": ["completion", "tools"],
    "details": { "family": "knowledge-fabric-ai", "families": ["knowledge-fabric-ai"] }
  }
  ```

  `modelfile`, `parameters`, `template` and `model_info` are stripped: each one names the real
  model or its prompt format. `capabilities` is passed through because kf-app's D12 capability
  probe needs to see `tools`.

### Chat

`POST /api/chat` is Ollama's own request and response, unchanged in shape — that is the whole
point of D-B, so that `AddOllamaChatCompletion(modelId, httpClient)` serves it with an address
and a bearer token. Streaming is passed through as `application/x-ndjson`
(`stream: true`, Ollama's default); tool definitions and tool-call payloads are untouched.

`options.num_predict` is clamped to the gateway's per-request maximum rather than refused: a
request asking for more gets the maximum. A request that asks for **nothing** also gets the
maximum, which is the point rather than a detail — the Ollama connector does not honour a
per-call cap (D19), so the requests that actually arrive carry no `num_predict` at all, and a
clamp that only lowered a value somebody had already chosen would leave every real turn
unbounded.

Nothing of the upstream reaches the application: no hostname, no model name, no key fragment,
no vendor error text, in any body or header, ever. Two consequences are worth stating, because
both are visible on the wire:

- **The response headers are the gateway's own.** No header the provider sent is passed on —
  not its `Server`, not a build or trace identifier, and not a `Set-Cookie` — and
  `Content-Type` is set by the gateway (`application/x-ndjson` when streaming,
  `application/json` when not) whatever the provider labelled the body. What comes back is the
  content type, the `X-KF-*` headers, and `X-KF-Error-Code` with `Retry-After` on a refusal.
- **A chunk carries the fields this document names, and no others.** The answer is rebuilt from
  them rather than filtered, so a field a provider adds later arrives dropped rather than
  forwarded. Ollama's `thinking` — the model's reasoning, streamed alongside an empty
  `content` — is the case this rule was written against: it is not in this contract, and it
  describes the model behind the alias by implication. Values are passed through untouched, so
  `tool_calls` and their arguments are unaffected.

Both are allow-lists on purpose. A list of things to strip would have to be re-audited against
every provider and every provider's next release; a list of what may pass cannot go stale in the
direction that leaks. Adding a field later is additive under the versioning rule below, which is
the reversible direction.

---

## Tiers and policy

Starting values. These are **policy**, not configuration: they live in the gateway's database
and change without a deploy, and G8's metrics will tune them.

| | Requests | Tokens | `num_predict` max |
|---|---|---|---|
| `evaluation` | 30 / minute | 1,000,000 per rolling 30 days | 4,096 |
| `standard` | 120 / minute | 10,000,000 per calendar month | 4,096 |
| `enterprise` | 120 / minute | 10,000,000 per calendar month | 4,096 |

**A `licensed` installation is served its licence's tier's row.** A licence whose `tier` attribute
is exactly `enterprise` gets the `enterprise` row. Every other accepted licence gets `standard`:
`tier` `standard`, no `tier` at all, and a value the gateway does not know, so `premium` and
`Enterprise` both read as `standard` (KnowledgeFabric/kf-admin `docs/License-Entitlements.md`,
rule 10). A tier is never a reason to refuse a licence, and it chooses this row and nothing else.
It is not a third tier on the wire either: `tier` and `X-KF-Tier` are `licensed` on both rows.

The two rows start equal, so shipping them moved nobody. Enterprise's is raised when its numbers
are decided. A row's allowance only goes up while a licence on that tier is in force.

A rolling 30 days is counted from the installation's first enrolment, in whole periods: re-enrolling
does not move it, and neither does a spell on the calendar month. A calendar month is UTC.
`X-KF-Tokens-Reset` is the end of the period running.

An application must read its allowance from the quota headers or `GET /v1/installation` and
never hardcode these numbers; they will change under it, deliberately.

**A licence may set its own AI limits.** A `licensed` installation whose licence carries any of
these attributes (KnowledgeFabric/kf-admin `docs/License-Entitlements.md`) is served them in place
of its row's numbers, whichever row that is:

| Attribute | Replaces | Reported in |
|---|---|---|
| `ai.tokens` | Tokens per budget period | `X-KF-Tokens-Limit`, `quota.tokens.limit` |
| `ai.period` | The budget period: `month`, a UTC calendar month, or `30d`, thirty days rolling as `evaluation`'s are | `X-KF-Tokens-Reset`, `quota.tokens.reset_at` |
| `ai.rpm` | Requests a minute | `X-KF-Requests-Limit`, `quota.requests.limit` |

What the licence leaves out is the row's. A value the licence carries but that cannot be read —
not a positive whole number in digits alone — is `0` and allows nothing: the licence is still
accepted, and every request is refused with `429`. An `ai.period` other than `month` or `30d` is
the row's period. The `num_predict` ceiling is never the licence's.

The limits last as long as the licence. When it expires or is removed, the installation is back
on the `evaluation` row; a licence refused with `422 licence_rejected` changes nothing. They are
per installation like everything else here: two installations carrying one licence each have the
whole of its allowance. There is no "unlimited" — a licence that means it carries a large number,
and the global brake still applies to it. The wire shape does not change: these are the same
headers and fields, with numbers that may come from the licence.

Every installation is its own blast radius: limits, budgets and revocation are per
installation, so what an abuser does costs the abuser their own allowance. The global brake
(`503 service_paused`) exists for the provider's sake and is not a substitute for that.

---

## Versioning

- `/v1` changes are **additive**: new fields, new error codes, new enum values. Nothing is
  renamed or removed. A breaking change is `/v2` beside `/v1`.
- Clients **must ignore** fields they do not know, and must treat an unknown `X-KF-Error-Code`
  as a generic failure of that HTTP status rather than a crash. That rule is what makes the
  additive promise usable.
- The gateway deploys before the application change that needs it.

---

## The stub gateway

`src/KnowledgeFabric.AiGateway.Stub` is this contract implemented in memory, in one binary,
with no provider behind it and no database under it. It exists so kf-app's tests (A2–A6) can
run against the contract instead of against a mock of their own — and so that a disagreement
between the two repositories shows up in a test run rather than in integration.

```bash
dotnet run --project src/KnowledgeFabric.AiGateway.Stub      # http://localhost:5080
```

kf-app's tests run it from a checkout of this repository rather than from a published image.
Nothing of ours is published to a public registry, and a checkout within the organisation costs
the same one credential a private registry would have — so the registry buys nothing.

Every stub response carries `X-KF-Stub: 1`, and the process logs a banner at startup. Nothing
about it should ever be mistaken for the gateway: it answers chat with a canned sentence.

### Canned behaviour

- Enrolment issues a real `kfg_` credential, stores only its hash, applies the payload rules
  above (unknown field → `400`), and keeps per-installation counters.
- `/api/chat` answers a fixed assistant sentence, streamed as NDJSON unless `stream` is `false`.
  When the request carries `tools` **and** the last user message contains `#toolcall`, the
  answer is a `tool_calls` message naming the first supplied tool with empty arguments — a
  tool-armed turn without a model.
- Token counts are deterministic: `prompt_eval_count` is the characters in the request's
  message contents divided by four, rounded up, and `eval_count` the same for the answer. They
  land in the counters, so `X-KF-Tokens-Used` moves the way it will in production.
- `/api/tags` and `/api/show` answer exactly the alias shapes above.
- The tier limits are the starting values in the table above, enforced for real. An accepted
  licence's `tier` chooses between `standard` and `enterprise`, and its `ai.tokens`, `ai.period`
  and `ai.rpm` apply over that row, all by the rules above. Each is an `<Attribute>` element under
  its `<LicenseAttributes>`, so a test can hand it
  `<License><Expiration>2027-09-01T00:00:00Z</Expiration><LicenseAttributes><Attribute name="tier">enterprise</Attribute><Attribute name="ai.rpm">2</Attribute></LicenseAttributes></License>`.

### The licence clock

A licence's `<Expiration>` is judged against today's date unless the stub is started with
`Stub__LicenceClock`, an ISO 8601 instant. kf-admin's contract fixtures are dated, and their
manifest states every verdict at one `evaluationInstant`, so a test that sends them starts the
stub with that instant and gets the same verdicts on any date:

```bash
Stub__LicenceClock=2026-07-01T12:00:00Z dotnet run --project src/KnowledgeFabric.AiGateway.Stub
```

Only licences read it. Rate windows, budgets and every reset the stub reports stay on the system
clock, because the application compares those with its own. A value that is not an instant stops
the stub at startup, and when it is set the stub says so in its log. Like `/stub/*`, it is outside
the contract: the gateway judges licences on its own clock.

### Switches

The control surface is `/stub/*`. It is unauthenticated and outside the contract — the real
gateway has no such paths.

| Call | Effect |
|---|---|
| `POST /stub/force` `{"code": "rate_limited", "times": 1}` | The next `times` matching requests are refused with that code, exactly as the table above describes it. `times` omitted means "until cleared". |
| `DELETE /stub/force` | Clears the forced code. |
| `POST /stub/policy` `{"tier": "evaluation", "requests_per_minute": 1, "token_budget": 100}` | Overrides a row's allowance, so a test reaches a limit in two requests rather than thirty-one. `tier` is `evaluation`, `standard` or `enterprise`; `licensed` moves both of the last two, and omitting it moves all three. |
| `GET /stub/state` | Enrolment count, per-installation counters and licence tier, the forced code and the policy in force — how a test asserts "enrolled exactly once". |
| `POST /stub/reset` | Forgets every installation, counter, override and forced code. |

A forced code applies to the surface it belongs to: `invalid_request`,
`app_version_unsupported` and `enrolment_rate_limited` to `POST /v1/installations`, and every
other code to the authenticated paths. That separation is what makes the re-enrolment test
work — force `installation_unknown` once, and the chat that follows fails while the enrolment
that follows it succeeds.

`X-KF-Stub-Force: <code>` on a single request does the same thing for that request only, for
tests that drive the stub over HTTP directly rather than through the application.

A forced code is delivered where the real one would be, which means a request forcing anything
other than `installation_unknown` or `installation_revoked` still has to authenticate first:
those two are the refusals that identify no installation, and everything else is refused after
the credential is recognised, with the quota headers the contract puts on it.
</file>

<file path="docs/Provisioning-Environments.md">
# Provisioning a gateway environment

How the AI Gateway's environments are built, in the order they have to be built, and what each
setting is for. Written to be followed rather than read: if a step here is wrong, fix the step.

Companion documents: [`API.md`](API.md) is the wire contract, and key rotation is
[`Runbook.md`](Runbook.md#rotate-the-provider-key), *Rotate the provider key*. The decisions behind
the shape are in the epic, [kf-app#954](https://github.com/KnowledgeFabric/kf-app/issues/954), and on
[#3](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/3).

> **Portal, not CLI.** Every step is written as Azure Portal navigation. Blade names drift
> between Portal releases; the setting and the reason for it do not. When the label has moved,
> match on what the step is trying to achieve.

---

## What an environment is

**Today there is one, under two names.** One App Service in West Europe, deployed from
`develop`, with both hostnames bound to it:

| | |
|---|---|
| Hostnames | `ai.knowledgefabric.io` **and** `ai-sb.knowledgefabric.io`, both on `app-stg-ai-gw` |
| Deployed from | `develop` |
| App Service plan | `P0v3` (Premium v3) — slots are available on it; none is created |
| Database | `kf_gateway_sandbox` |
| GitHub Environment | `sandbox` |

Production is deferred until a pilot justifies a second App Service. Binding the production
hostname here is what makes that invisible to installations: `docs/API.md`'s compiled base
address stays `https://ai.knowledgefabric.io` and needs no exception for the deferral.

**The price is that there is no test environment.** A risky deploy, a schema change or a
provider switch has nowhere to go but the service real installations are using. The name
`ai-sb`, and the `stg` in every resource name, no longer mean what they say. Lower the DNS TTL
on `ai` while this holds, so the eventual cutover is short.

When production is built, it looks like this, and `ai.knowledgefabric.io` moves to it:

| | Production | The existing environment |
|---|---|---|
| Hostname | `ai.knowledgefabric.io` | `ai-sb.knowledgefabric.io` |
| Deployed from | `main` | `develop` |
| App Service plan | Slots required | `P0v3`, which has them |
| Database | `kf_gateway` (created, unused until then) | `kf_gateway_sandbox` |
| GitHub Environment | `production` | `sandbox` |

A custom hostname binds to **one** App Service at a time, so moving `ai.knowledgefabric.io`
means unbinding, rebinding, revalidating and a new managed certificate — a gap with the hostname
down. Do it before a pilot, not after.

Production needs a tier with deployment slots for one reason — a slot swap makes a key rotation
cost nobody a turn, where a restart drops every stream in flight. The existing plan already has
them; what is missing is a slot and the deploy step that swaps it, which is #17's.

Everything lives in **West Europe**, and every database lives on **one shared PostgreSQL
Flexible Server**. Region follows the App Service, not the provider: the provider is a hosted
service with no endpoint of ours to sit beside.

### Current state

| Resource | Status |
|---|---|
| App Service `app-stg-ai-gw`, `ai-sb.knowledgefabric.io`, certificate bound | **Done** |
| `ai.knowledgefabric.io` on the same App Service, certificate bound | **Done** — verified serving `CN=ai.knowledgefabric.io` |
| PostgreSQL Flexible Server, West Europe, Burstable B1ms, PostgreSQL 18 | **Done** |
| The two databases and their logins (A2) | **Done** |
| App registration, federated credentials, role assignment | **Done** |
| GitHub Environment `sandbox` and its secrets | **Done** |
| Application Insights `app-stg-ai-gw`, on its own workspace `log-aigw-stg-weu-1` | **Done** — created with the App Service and reused; agent collection removed |
| Alerts and their action group (B7) | **Not yet**, and none has fired |
| A production App Service | Deferred until a pilot |

---

## Before you start

- A subscription, and the resource group for the environment. Staging and sandbox resources are
  all in **`rg-kf-staging-weu-01`** — every one of them, so a resource of ours outside it is a
  mistake rather than a variation. The Portal has defaulted these create blades to West US 3 in
  the past, and the group's name says `weu`: check the region on every one of them regardless of
  what the group is called.
- Permission to create an app registration in Microsoft Entra ID, and to assign roles on the
  App Service. These are usually different people's rights; find out before you begin rather
  than halfway through.
- Access to DNS for `knowledgefabric.io`.
- Admin of the GitHub repository, to create Environments and their secrets.

---

## Part A — Once, shared by every environment

### A1. PostgreSQL Flexible Server

One server holds every environment's database. That is a cost decision, and it carries two
consequences that must be understood before it is made — see **What sharing costs** below.

*Create a resource → Azure Database for PostgreSQL → Flexible server.*

| Setting | Value | Why |
|---|---|---|
| Region | West Europe | Beside the App Services. A mismatch costs a round trip on every query |
| Workload type | Development | Presets the smallest compute; override storage below |
| Compute + storage | **Burstable B1ms**, **32 GiB** | The smallest thing that runs. Storage can be grown later but **never shrunk**, so start at the floor |
| High availability | Off | Not offered on Burstable |
| Authentication | PostgreSQL authentication | An Entra-only server cannot hand a connection string to App Service |
| Admin username | Not `postgres`, not `admin` | This account creates the per-database logins and is then not used again |
| Backup retention | **35 days** | Free at this size, and five weeks is the realistic window for noticing a bad migration |
| Geo-redundancy | **Off** | **Create-time only — it cannot be added later.** Losing the region costs every installation a re-enrolment, which is survivable, and no prompt or response is stored to lose |
| Connectivity | **Public access** | VNet integration is the tidier end state and needs Standard App Service; this is what starts |

On the **Networking** tab, tick **Allow public access from any Azure service within Azure to
this server**. That admits any Azure-hosted client, not only ours — accepted because App
Service's outbound addresses are a shared set that changes, and an IP rule that goes stale
means a gateway that *will not boot*, since the schema migrates before Kestrel opens. The
database still requires credentials and TLS.

**Add your own client IP** with the *+ Add current client IP address* link — it is a link, not a
checkbox, and nothing is added until you click it. You need it to create the databases in A2.
Name the rule for yourself and delete it once A2 is done: the service connects through the
Azure-services rule, and office addresses get reassigned to other people.

**Do not click *+ Add 0.0.0.0 - 255.255.255.255*,** which sits immediately beside it. That opens
port 5432 to the whole internet rather than to Azure.

Record the server name; you need it for every connection string.

### A2. The databases and their logins

One database and one login per environment. **A login must not be able to reach the other
environment's database** — that is what recovers most of the isolation a separate server would
have given, and it is the condition on which sharing one server is acceptable at all.

**Getting a `psql` prompt.** The Overview blade offers *Connect from VS Code* and a card that
only shows connection strings; there is no Cloud Shell button on it. Open **Cloud Shell** from
the portal's top bar (the `>_` icon, or the *CLI / PS* toolbar button), choose **Bash**, and
connect. Cloud Shell runs inside Azure, so the Azure-services firewall rule already admits it —
no client-IP rule needed for this step.

```bash
psql "host=<server>.postgres.database.azure.com port=5432 dbname=postgres user=<admin> sslmode=require"
```

The admin username is plain, with no `@servername` suffix — that was the old Single Server. A
`psql` a major version behind the server is normal in Cloud Shell and harmless for this work,
though some meta-commands break on it (below).

Generate the two passwords from a password manager, **40 characters of letters and digits with
no symbols**. That is far more entropy than needed, and it avoids every delimiter this credential
has to survive on its way to the server: the shell that exports it, the Npgsql connection-string
parser (`;` ends a field), the Portal's application-settings box and `psql` itself. The prompt will be
`postgres=>` rather than `=#`, because the admin is a member of `azure_pg_admin` rather than a
superuser; that is expected and grants everything this step needs.

```sql
CREATE ROLE kf_gateway_app         LOGIN PASSWORD '...';
CREATE ROLE kf_gateway_sandbox_app LOGIN PASSWORD '...';

CREATE DATABASE kf_gateway;
REVOKE CONNECT ON DATABASE kf_gateway FROM PUBLIC;
GRANT  CONNECT ON DATABASE kf_gateway TO kf_gateway_app;
```

Now, still as the admin, step into the database and hand over its schema. Migrations create
tables in `public`, and on Azure that schema is **not** owned by `pg_database_owner` the way a
stock PostgreSQL 15+ cluster would have it — so owning the database is not enough, and a
migration that gets this far fails with `42501: permission denied for schema public`.

```
\c kf_gateway
```
```sql
ALTER SCHEMA public OWNER TO kf_gateway_app;
```

Then back out and transfer the database itself, which is the last thing you do to it:

```
\c postgres
```
```sql
ALTER DATABASE kf_gateway OWNER TO kf_gateway_app;
```

Repeat all of that for `kf_gateway_sandbox` and `kf_gateway_sandbox_app`.

**The order is the whole trick here**, and getting it wrong is recoverable but tedious:

- Roles first, because a database cannot be handed to a role that does not exist.
- `REVOKE` and `GRANT` while the admin still owns the database — on a database you no longer own,
  they are refused.
- The **schema** changes hands before the **database** does. Once the database belongs to the app
  role, the admin is no longer its owner and, since `azure_pg_admin` is not a superuser, may be
  unable to connect at all — leaving no way in to fix the schema. If you have already got into
  that state, let the admin back in from `postgres` by acting as the role it created:

  ```sql
  SET ROLE kf_gateway_sandbox_app;
  GRANT CONNECT ON DATABASE kf_gateway_sandbox TO <admin>;
  RESET ROLE;
  ```

**Check the result.** `\l` is broken in Cloud Shell against a PostgreSQL 17 or later server —
`psql` 16 selects `d.daticulocale`, which was renamed to `datlocale` — so read the catalogue
directly:

```sql
SELECT datname, pg_get_userbyid(datdba) AS owner, datacl
FROM   pg_database
WHERE  datname LIKE 'kf_gateway%';
```

Each database should be owned by its own app role, with an ACL like
`{=T/kf_gateway_app,kf_gateway_app=CTc/kf_gateway_app}`. The empty left side is PUBLIC: it must
hold `T` (TEMPORARY) and **not** `c` (CONNECT), which is the default the `REVOKE` removed. The
leftover `T` is harmless, since a temporary table needs a connection first. Neither role should
appear in the other database's ACL.

Then prove it rather than infer it:

```
\c kf_gateway_sandbox kf_gateway_app
```

This must be refused with `permission denied for database`. If it connects, the environments are
not separated and the shared server is not safe to use.

**The check that proves all of it** is running the service against the database, since that is
what production does — the schema migrates at startup, before Kestrel opens. With your client-IP
rule still in place:

```bash
Database__ConnectionString='Host=<server>.postgres.database.azure.com;Database=kf_gateway_sandbox;Username=kf_gateway_sandbox_app;Password=...;SslMode=Require' \
  dotnet run --project src/KnowledgeFabric.AiGateway
```

Single quotes, so the shell leaves the password alone. You are looking for `Applying migration`
followed by `Database schema is current.` and then `Now listening on`. Anything else and the
process exits rather than serving, which is the designed behaviour and much better discovered
here than during a deploy.

This is also where the driver was confirmed against the server: **Npgsql 8.0.11 migrates cleanly
on PostgreSQL 18.6**, so nothing here needs EF Core 9.

The connection string each environment needs, as one line:

```
Host=<server>.postgres.database.azure.com;Database=kf_gateway;Username=kf_gateway_app;Password=...;SslMode=Require
```

### What sharing costs

Two things follow from one server, and both belong in anyone's head before they act on it:

1. **A point-in-time restore acts on the server, not a database.** Recovering sandbox to last
   Tuesday also rolls production's database back to last Tuesday *on the restored copy*. The
   restore procedure is therefore: restore to a new server → move only the intended database
   across → repoint only that connection string. Never repoint both.
2. **CPU credits are shared.** Burstable accrues credits and throttles hard once they are spent,
   so a sandbox load test can throttle production. **Before the first customer installation,
   split the servers or leave Burstable.** This is a scheduled decision, not a risk to carry
   indefinitely.

---

## Part B — Per environment

Do these in order. DNS is the long-lead item but needs the App Service to exist first, because
the records point at it.

### B1. The App Service

*Create a resource → Web App.*

| Setting | Value |
|---|---|
| Publish | **Code** (not Container — this service has no image) |
| Runtime stack | .NET 8 (LTS) |
| Operating System | Linux |
| Region | West Europe |
| Plan | Anything with **deployment slots** — Standard or higher. The existing one is `P0v3` (Premium v3), which has them |

Then, on the created App Service:

- **Settings → Configuration → General settings**: **Always On = On**. Without it the platform
  idles the process out and the first request after a quiet spell pays a cold start — on a
  gateway in the hot path of every chat, that is felt.
- **Settings → Configuration → Health check** tab: path **`/health`**, so the platform takes an
  unhealthy instance out of rotation. `/health` deliberately does not check the database or the provider: it must
  answer even when either is down, or an outage in one would hide the real failure.
- **Settings → Configuration**: **HTTPS Only = On**.
- **Scale out**: **one instance, and no autoscale rule.** The request rate limiter holds its
  window in process, so a second instance silently doubles every limit and makes
  `X-KF-Requests-Remaining` a fiction — a contract-visible breach of D-C with nothing failing
  loudly to announce it. The plan is Premium v3, where scaling out is one click and autoscale is
  available, so this needs watching rather than remembering:

  **Add an alert on instance count** — B7's *Second instance*, on the App Service **plan**,
  **maximum > 1** over 5 minutes. The rule is the whole of the enforcement — nothing in the code can
  tell how many copies of it are running.

  **The day a second instance is genuinely wanted, the limiter and the global brake move to shared
  backing first** — the database or Redis — and only then does the plan scale. Scaling out before
  that is a silent quota breach, not a performance win. The token budget is already database-backed
  and is unaffected by instance count.

  **A restart or a slot swap forgets every window.** `X-KF-Requests-Remaining` returns to full and
  a few requests are over-admitted for one window. It is bounded, rare, and errs toward
  availability, so it is accepted — but it belongs in the runbook rather than in somebody's memory.
  The global brake is the opposite case by design: it is derived from a persisted counter, so a
  restart does not release it (docs/Admin.md).
- **Deployment → Deployment slots**: a slot named `staging` is what makes a key rotation a swap
  rather than a restart. **None exists today** — the existing plan supports one and the deploy
  does not use one, so every deploy and every key change is a restart. Creating it and adding the
  swap to `deploy.yml` is #17's, deliberately deferred while nothing is attached to the service.
- **Settings → Configuration → General settings**: turn **SCM Basic Auth Publishing** off. The
  deploy authenticates with OIDC; a publish profile is a long-lived credential this project has
  no use for.

### B2. DNS and the managed certificate

1. On the App Service, **Settings → Custom domains → Add custom domain**, and read the two
   values the Portal shows: the App Service default hostname, and the **custom domain
   verification ID**.
2. At the DNS provider, create both records for the hostname:
   - `CNAME` → the App Service default hostname
   - `TXT` on `asuid.<hostname>` → the verification ID
3. Back in the Portal, validate and add the domain.
4. **Add a free App Service Managed Certificate** for the hostname, then bind it (SNI SSL).

   **These are two steps even though the dialog presents them as one.** Selecting *App Service
   Managed Certificate* while adding the domain can still leave it listed as **No binding** —
   the certificate is issued but nothing binds it to the hostname. Use the *Add binding* link
   against that row: certificate for this hostname, TLS/SSL type **SNI SSL**.

   **Then give it a few minutes.** A new binding takes a little while to reach App Service's
   front ends. Until it does, the hostname is served the platform's own
   `CN=*.azurewebsites.net` certificate and `curl` fails with *no alternative certificate
   subject name matches target host name* — which reads like a misconfiguration and is only
   impatience. The domain is right when *Custom domains* shows **Secured** with a certificate
   named for that hostname, and:

   ```bash
   curl -i https://<hostname>/health
   curl -vI https://<hostname>/health 2>&1 | grep -i 'subject:'
   ```

   answer 200 and name the hostname rather than `*.azurewebsites.net`.

DNS propagation is why this ticket started in Phase 0. If validation fails, it is almost always
a record that has not propagated yet — wait rather than changing anything.

**Repeat all of it for `ai.knowledgefabric.io` on the same App Service**, while production is
deferred: an App Service holds several custom domains, each with its own certificate. A CNAME
from one hostname to the other does **not** work — App Service routes by `Host` header and
refuses a hostname that is not bound to it, so the production hostname has to be a binding here
rather than an alias elsewhere. Set a short TTL on it: when production is built, that record
moves, and a custom hostname binds to one App Service at a time.

### B3. Application Insights

**There is probably one already.** The App Service create blade offers Application Insights and
creates it by default, so the resource usually exists before anyone reads this step, and
`APPLICATIONINSIGHTS_CONNECTION_STRING` is usually already set. Reuse it rather than creating a
second — this step is then three checks and one deletion, not a create.

> **It has the App Service's name.** The auto-created resource is named after the App Service, so
> `app-stg-ai-gw` is *two* resources of different types. Application Insights has no application
> settings at all — it does not run code — so every setting below belongs to the App Service, and
> the App Insights blades below are only for where telemetry lands. Tell them apart by the type
> column in the resource group, or by the left nav: *Deployment Center* and *Environment
> variables* is the App Service, *Logs* and *Live Metrics* is Application Insights.

#### Delete the agent settings

The one step here that changes behaviour. On the **App Service**, *Settings → Environment
variables → App settings*, remove:

```
ApplicationInsightsAgent_EXTENSION_VERSION
XDT_MicrosoftApplicationInsights_Mode
```

These are agent-based ("codeless") collection, which the App Service turns on when it creates the
resource for you. The gateway instruments itself — the Azure Monitor OpenTelemetry distro in
`Telemetry/` — and an agent attached on top of that **reports every request twice**. Keep
`APPLICATIONINSIGHTS_CONNECTION_STRING`: it is the only thing the gateway reads, and B4 is where
it is set by hand if it is not already there.

**Apply, and confirm the dialog.** The blade stages a deletion exactly as it stages an addition,
and skipping the confirmation leaves the settings in force.

#### Give it a workspace of its own

Check the App Insights resource's *Overview*: it should say **Workspace-based** (classic is
retired), and be in **West Europe**, which is where the data then lives — a resource that landed
elsewhere is a data-residency decision, not a latency one, and telemetry is not in the hot path.

The auto-created resource points at the **subscription default workspace**,
`DefaultWorkspace-<subscription-id>-WEU`. Move it to one of this environment's own —
`log-aigw-stg-weu-1` — created in the environment's resource group and region:

- **Retention is a workspace setting**, so the 30 days below would re-set retention for everything
  else writing to the default workspace, and anyone raising it for their own resource would
  silently break D-D's claim for us. Table-level retention does not separate us either: every
  Application Insights resource on a workspace shares those tables.
- **Read access is a workspace grant**, and the default workspace is the one that accumulates
  broad grants precisely because it is the default. See what that exposes, below.
- **Production would otherwise share it**, which is the separation this document keeps per
  environment everywhere else.

*Application Insights → Properties → Change Workspace.* Two things worth knowing rather than
discovering: the connection string and instrumentation key belong to the Application Insights
resource, not to the workspace, so **nothing needs redeploying** and the App Service setting stays
valid. And telemetry already ingested **stays in the old workspace** — it is not migrated, so do
this while there is nothing in there worth keeping.

#### Set retention

On the workspace, *Usage and estimated costs → Data Retention*: **30 days**. D-D's privacy claim in
kf-app says request metadata is kept 30 days, and this setting is what makes that true rather than
aspirational (G8).

**A new workspace has defaulted to 30 already**, so this is usually a check rather than a change —
but check it rather than assuming, because the default has moved between Portal releases and
nothing announces it when it does. Retention past the first month is billed per GB, so 30 is the
cheap answer as well as the correct one. The counters are database rows and are unaffected by any
of this, the daily usage ledger included: it is what keeps a month's figures once they leave this
workspace, and D-D keeps counters indefinitely ([#41](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/41)).

#### What holds from the first day it exists

**An absent connection string is valid and does not fail the process.** Unlike the database, a
gateway with nowhere to send telemetry still serves every request correctly, which is what a
laptop and `dotnet test` are. What it costs an environment that *should* have a sink is a silence
in Application Insights — which is why B7's *Telemetry silent* alert is what notices, rather than a
startup validation nobody would see.

**Sampling is off, by decision.** The default samples, and the records it drops are exactly the
ones abuse response and spend estimation are read from: a 429 storm and a spend anomaly are rare by
definition, which is what a sampler discards first. `SamplingRatio` is pinned to `1.0` and
`TracesPerSecond` cleared in `Telemetry/TelemetryServiceCollectionExtensions.cs`. Both, because
since the distro's 1.5.0 the default is rate-limited sampling at five traces a second, and it
overrides the ratio: with only the ratio set, a burst kept five requests a second and dropped the
rest. `TelemetryTests` sends a burst through a real exporter to a stand-in endpoint, so an upgrade
that changes the default again fails there rather than in the workspace. The consequence is that volume
has to be controlled deliberately somewhere else, so a **passing** `/health` is dropped at the
source — the platform polls it continuously on two schedules, and it is the least informative item
there is. A **failing** one is kept, because that is the signal worth alerting on.

**Read access to this resource is a decision, not a formality.** Dependency telemetry records the
real upstream URL, so the provider's hostname and the real model name are in here — the one thing
the `knowledge-fabric-ai` alias exists to keep from the application (D15, invariant 3). That is
not a breach of it: invariant 3 governs what reaches a response body or header, and the timings
are worth having, so dependency tracking stays on. It does mean whoever can query this workspace
can read what the gateway fronts.

**No body logging.** A prompt or a response never reaches a log, a metric label, a span attribute
or an error message, and telemetry is a sink like any other (invariant 2). `TelemetryTests`
collects the exported spans in-process so that G5's sentinel test can assert against them and not
only against `ILogger`.

#### Verifying it

Not with `/health`: a passing one is dropped by design, so an empty result there reads as broken
when it is correct. Use something that leaves a span, once the service is deployed:

```bash
curl -s -o /dev/null -w '%{http_code}\n' https://ai-sb.knowledgefabric.io/api/generate    # 404
curl -s -o /dev/null -w '%{http_code}\n' https://ai-sb.knowledgefabric.io/v1/installation # 401
```

Then in *Logs*:

```kusto
requests | where timestamp > ago(15m) | project timestamp, name, url, resultCode
```

Both should appear, and no `/health` rows. `/health` rows appearing means agent-based collection is
still on somewhere — the deletion above did not take, or was not confirmed.

### B4. Application settings

**Settings → Environment variables → App settings**, then *+ Add*. (Not *Configuration*, which
now holds only platform settings — the portal moved these out of it.) They are set here, by hand,
and **the deploy never writes them** — it ships code only. Nested configuration uses a double underscore,
which the runtime maps back to `:`.

| Setting | Value |
|---|---|
| `Database__ConnectionString` | The line from A2, for this environment's database |
| `Forwarding__UpstreamAddress` | The provider address. Required: the process will not start without it |
| `Forwarding__Model` | The model the `knowledge-fabric-ai` alias resolves to. Required, and never seen by the application |
| `AI_GATEWAY_OLLAMA_API_KEY` | The provider key — G5 injects it as the upstream bearer token |
| `APPLICATIONINSIGHTS_CONNECTION_STRING` | The connection string from B3. Written for you by the *Application Insights* blade; absent is valid and means no telemetry sink |

**A setting is not live until you confirm it.** The blade stages your edits, *Apply* opens a
confirmation, and only then does the App Service restart and the process see them. Skipping that
dialog leaves the old value in force. Since G5 there is no compiled-in default to fall back on:
an App Service missing either forwarding setting fails to start and the deploy's health check
fails with it, which is the loud version of the same mistake.

> **G5 renamed the upstream setting.** `ReverseProxy__Clusters__provider__Destinations__upstream__Address`
> is gone — the gateway no longer forwards through YARP — and `Forwarding__UpstreamAddress` and
> `Forwarding__Model` replace it. **Both must be added by hand before the deploy that carries G5
> restarts the app**, or it will not start. The old setting can be deleted at the same time; it is
> read by nothing.

The connection string is as much a secret as the provider key and is handled the same way.
Neither is ever committed, and neither reaches a workflow: that is what makes "never in a CI
log" a property of the design rather than a promise about masking. It is also why rotating the key
is a change to this setting and never a commit: [`Runbook.md`](Runbook.md#rotate-the-provider-key),
*Rotate the provider key*. Today that change is a restart; once there is a slot (#17), it is a swap.

> **Sandbox may now be pointed at the real provider.** Until G5 all three paths were plain
> passthroughs, so a real upstream would have returned the account's actual model catalogue on
> `/api/tags` and the real model name in every `/api/chat` chunk. G5 removes that: `/api/show`
> and `/api/tags` are answered by the gateway from the alias and never forwarded, and every chat
> chunk is rebuilt from the contract's own fields. Switching the upstream over is what #5's
> remaining deployed checks are for, and it wants the two settings above set together.

### B5. App registration and federated credentials

One app registration **per environment**, so a sandbox deploy credential cannot reach
production. (One registration with two federated credentials also works and is less to manage;
it gives up that separation.)

1. *Microsoft Entra ID → App registrations → New registration.* Name it for the environment,
   e.g. `kf-ai-gateway-deploy-sandbox`. No redirect URI.
2. *Certificates & secrets → **Federated credentials** tab → Add credential.* Choose the
   **GitHub Actions deploying Azure resources** scenario and fill in:
   - Organization `KnowledgeFabric`, Repository `kf-ai-gateway`
   - **Organization ID** `142328979`, **Repository ID** `1356096016` — the form asks for
     GitHub's numeric ids, which are awkward to find for a private repository. They come from
     `api.github.com/orgs/<org>` and `api.github.com/repos/<org>/<repo>`.
   - Entity type **Environment**
   - Environment name **exactly** `production` or `sandbox`

   **Create this credential twice, with both subject formats.** The blade builds a subject in
   GitHub's *immutable claims* form, which embeds those numeric ids:

   ```
   repo:KnowledgeFabric@142328979/kf-ai-gateway@1356096016:environment:sandbox
   ```

   GitHub only sends that form if the organisation has opted into immutable OIDC claims.
   Otherwise it sends the classic one:

   ```
   repo:KnowledgeFabric/kf-ai-gateway:environment:sandbox
   ```

   For the second credential, use the *Edit (optional)* link beside **Subject identifier** and
   type the classic form. Whichever GitHub actually sends then matches one of them. Two
   credentials cost nothing — each is the same narrow statement about one repository and one
   environment — and a mismatch otherwise surfaces as an unhelpful `azure/login` failure at the
   very end of a deploy, after the publish has already happened.

   Either way the environment name is compared literally, so it must match the GitHub
   Environment character for character. Issuer and Audience are correct as they come:
   `https://token.actions.githubusercontent.com` and `api://AzureADTokenExchange`.
3. **Do not create a client secret.** The point of OIDC is that there is no stored credential.
   Client secrets live on a different tab of the same blade; the federated one is the other.
4. On the **App Service** (not the resource group, and not the subscription):
   *Access control (IAM) → Add role assignment → **Website Contributor** → assign to this app
   registration.* Scoping to the one App Service is what keeps the blast radius to one
   environment.
5. Record from the registration's Overview: **Application (client) ID** and **Directory
   (tenant) ID**. Take the **Subscription ID** from the subscription blade.

### B6. GitHub Environment and its secrets

*Repository → Settings → Environments → New environment*, named **exactly** as in B5.

**Secrets:**

| Secret | From |
|---|---|
| `AZURE_CLIENT_ID` | B5 step 5 |
| `AZURE_TENANT_ID` | B5 step 5 |
| `AZURE_SUBSCRIPTION_ID` | B5 step 5 |

**Variables** — not secrets, because masking them would blank the deployed URL out of exactly
the log a failed deploy needs to show:

| Variable | From |
|---|---|
| `AZURE_WEBAPP_NAME` | The App Service resource name from B1 |
| `AZURE_RESOURCE_GROUP` | The resource group holding it |

**Nothing here is a credential for the gateway itself.** The provider key and the connection
string live in App Service configuration (B4) and never enter GitHub, so a workflow log has
nothing to leak. What these grant is the right to deploy code to one App Service, scoped by the
role assignment in B5 step 4.

On `production`, add a **required reviewer** so a deploy to it is a decision someone makes.

### B7. Alerts

The rules [`Runbook.md`](Runbook.md) lists, one place for them to notify, and proof that each one
fires. **Before there is an alert, nobody hears about any of it**: the telemetry arrives and sits in
the workspace unread.

The rules' queries, thresholds and what to do when each fires are in the runbook, not here: this
step creates them, and the runbook is what is read when one fires. Create them from the runbook's
text, so the two start the same.

#### The action group

*Monitor → Alerts → Action groups → Create*, in the environment's resource group:

| Setting | Value |
|---|---|
| Name | `ag-aigw-stg-weu-1` |
| Display name | `aigw-stg` (twelve characters at most; it prefixes every SMS) |
| Notifications | *Email/SMS message/Push/Voice*: an email to each person who answers for the gateway. A person, not a shared mailbox nobody reads |
| Actions | None. Every alert here asks a person to decide something |

#### The log search rules

Five rules, each on the **Application Insights** resource `app-stg-ai-gw` — not the workspace, so
that the runbook's queries find `requests` and `traces` by those names. *Application Insights →
Alerts → Create → Alert rule*:

- **Condition**: *Custom log search*, and paste the query from the runbook.
- **Measurement**: *Table rows*, aggregation *Count*, and the look-back below as the *aggregation
  granularity*. No dimension splitting.
- **Alert logic**: the operator and threshold below, evaluated at the frequency below.
- **Actions**: `ag-aigw-stg-weu-1`.
- **Details**: the name and severity below, region West Europe, and **automatically resolve
  alerts** on, so a rule clears itself once its condition does.

| Rule | Runbook section | Look back | Evaluate every | Fires when rows are | Severity |
|---|---|---|---|---|---|
| `alert-aigw-stg-brake-tripped` | Global brake tripped | 5 minutes | 5 minutes | greater than 0 | 1 |
| `alert-aigw-stg-upstream-failures` | Upstream failures | 15 minutes | 5 minutes | greater than 0 | 2 |
| `alert-aigw-stg-spend-anomaly` | Spend anomaly | 1 hour | 1 hour | greater than 0 | 2 |
| `alert-aigw-stg-telemetry-silent` | Telemetry silent | 1 hour | 15 minutes | **less than 1** | 2 |
| `alert-aigw-stg-enrolment-spike` | Enrolment spike | 1 hour | 15 minutes | greater than 0 | 3 |

#### The metric rules

Three, on the resources themselves rather than on Application Insights, because the platform
measures them whether or not the gateway is running:

| Rule | On | Signal | Condition | Look back / every | Severity |
|---|---|---|---|---|---|
| `alert-aigw-stg-health-check` | The App Service `app-stg-ai-gw` | *Health check status* | Average **less than 100** | 5 minutes / 1 minute | 1 |
| `alert-aigw-stg-instance-count` | The App Service **plan** | *Instance Count* | Maximum **greater than 1** | 5 minutes / 1 minute | 2 |
| `alert-<server>-storage` | The Flexible Server from A1 | *Storage percent* | Average **greater than 80** | 1 hour / 15 minutes | 2 |

The instance-count rule is the one B1 asks for: if it was created then, point it at the action
group rather than making a second. The storage rule is the **server's**, not this environment's:
create it once, and a second environment does not repeat it. Name it after the server.

#### Making each one fire

*Done when* on #8 is that each alert has fired once, deliberately. A rule that has never fired is a
rule nobody knows works: a dimension name misspelt in its query, or a table it cannot see, matches
nothing and says nothing.

**Every one of these disturbs the environment**, and there is only one. Do them before
installations depend on it — before kf-app#969 cuts over — or not at all. Each takes an alert
email as its proof, and the alert then resolves on its own once the change is undone.

What they need, from the admin surface ([`Admin.md`](Admin.md)): `$ADMIN`, `$TOKEN` (the full
admin token) and `$OPERATOR`. And an installation of your own to chat with:

```bash
GW=https://ai-sb.knowledgefabric.io
INSTALLATION=$(uuidgen | tr 'A-Z' 'a-z')
CRED=$(curl -s -X POST "$GW/v1/installations" -H 'Content-Type: application/json' \
  -d "{\"installation_id\":\"$INSTALLATION\",\"app_version\":\"1.6.2\",\"licence\":null}" | jq -r .credential)
chat() { curl -s -o /dev/null -w '%{http_code} %header{x-kf-error-code}\n' -X POST "$GW/api/chat" \
  -H "Authorization: Bearer $CRED" -H 'Content-Type: application/json' \
  -d '{"model":"knowledge-fabric-ai","stream":false,"messages":[{"role":"user","content":"Say hello."}]}'; }
chat    # 200, and the month's spend is no longer zero, which the brake needs below
```

1. **Global brake tripped.** Note `brake.ceiling` from `GET /admin/status`, then set
   `global_token_ceiling` to `1` ([`Admin.md`](Admin.md), *Release the global brake*, the same `PUT`
   with `1`). `chat` answers `503 service_paused`; the email arrives within ten minutes. Put the
   ceiling back as it was.
2. **Upstream failures.** Note the App Service setting `Forwarding__UpstreamAddress` — not a secret
   — and set it to `https://upstream.invalid/`. Saving restarts the app. `chat` three times: each is
   `502 upstream_unavailable`. The email arrives within ten minutes. Put the address back, and `chat`
   answers `200` again.
3. **Health check failing.** Add the App Service setting `Forwarding__FirstByteTimeout` = `00:10:00`.
   It is past the platform's idle timeout, so the process refuses to start, and every request —
   `/health` included — fails. The email arrives within ten minutes. Delete the setting; `/health`
   answers `200` again. If no email came and the *Health check status* chart shows a gap rather than
   a fall to zero, the platform reports nothing for a process that never started: record that on #8,
   because *Telemetry silent* is then the only alert that notices one.
4. **Enrolment spike.** In the rule's query, set `threshold = 0`, and enrol one more installation
   (the `curl` above, with a new id). The email arrives within twenty minutes. Put `threshold = 10`
   back.
5. **Spend anomaly.** `chat` once, so that today has spent something. In the rule's query, set
   `ratio = -1.0` and `floor = 0`, which any reading with a token in it satisfies. The next spend
   report is at most a quarter of an hour away and the rule runs hourly, so the email arrives within
   an hour and a quarter. Put `3.0` and `1000000` back.
6. **Telemetry silent.** In the rule's query, append `| where timestamp < ago(2d)`, which nothing in
   a one-hour window satisfies. The email arrives within twenty minutes. Remove it.
7. **Second instance.** On the plan, *Scale out*: a manual count of `2`. The email arrives within
   ten minutes. Put it back to `1`. While there are two, each holds its own request windows, so every
   rate limit is briefly double; that is what the alert is for.
8. **Database storage.** Set the rule's threshold to `1`. The email arrives within twenty minutes.
   Put `80` back.

Steps 1, 2, 3 and 7 break the thing each alert watches. The rest change the rule to fire on what is
already there, because the real condition is expensive (a day of spend, an hour of silence, a full
disk) or is somebody else's to cause. For those, what is proven is that the query finds its data and
the notification reaches a person, which is the part that fails silently.

---

## Adding a third environment

Everything in **Part B**, plus a database and login from **A2**. Nothing in Part A is repeated:
the server is shared, and so is B7's storage alert. Two things are easy to forget — the branch that deploys it needs adding
to `deploy.yml`, and its GitHub Environment name must match its federated credential subject.

Before adding one, check the shared-server consequences above still hold. A third environment
on the same Burstable server is a third claim on the same CPU credits.

---

## What is deliberately not here

- **The provider key's value.** It exists in the provider account and in the App Service's
  application setting (B4), set there by hand. Nowhere else, ever: not in GitHub (B6) and not in a
  deploy. That is invariant 1, and it is the reason this service exists.
- **A container image for the service.** The gateway deploys as a `dotnet publish` package. The
  only image this repository builds is the stub's, which kf-app's tests pull.
- **Key rotation.** [`Runbook.md`](Runbook.md#rotate-the-provider-key), *Rotate the provider key*:
  B4 sets the key once, and the runbook changes it, planned or after a leak.
</file>

<file path="docs/Runbook.md">
# Runbook — the alerts, and what to do when one fires

What watches the gateway, what each alert means, and which lever to reach for when it fires
([#8](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/8), G8). Start at the alert that
fired.

The levers themselves (revoke, the policy rows, the brake, the minimum version) are
[`Admin.md`](Admin.md)'s, and this document links to them rather than repeating them: it says
*when* to pull one, and `Admin.md` says *how*. Creating the rules is
[`Provisioning-Environments.md`](Provisioning-Environments.md) §B7, which also says how to make
each one fire on purpose.

---

## Where to look

| Question | Where |
|---|---|
| Is it up, what is deployed, is the brake tripped, is today spending more than usual, is telemetry configured? | `GET /admin/status` ([`Admin.md`](Admin.md), *The status*) |
| What happened in the last minutes or hours, request by request? | Application Insights `app-stg-ai-gw` → *Logs*, with the queries below |
| What did a day, a month or an installation cost? | `GET /admin/usage/daily` and `/admin/usage/summary` ([`Admin.md`](Admin.md), *Usage history*) |

The queries here use the **Application Insights resource's** table names — `requests`, `traces` —
and are run from its *Logs* blade. On the workspace `log-aigw-stg-weu-1` the same data is
`AppRequests` and `AppTraces`, with `Properties` in place of `customDimensions`.

Application Insights keeps **30 days** (D-D; §B3 sets it). The daily usage ledger behind
`/admin/usage` keeps its counters indefinitely, so anything older than a month, and any question
about what a day *cost*, is answered there. The two are not meant to agree to the token: the ledger
is the authority, and the workspace is where alerts fire from.

### What the gateway adds to each request

Beyond what the instrumentation records by itself, the gateway puts these on the request, where
they arrive as custom dimensions (`Telemetry/SpanTags.cs`):

| Custom dimension | On | Holds |
|---|---|---|
| `kf.installation.id` | Every request that names an installation: every authenticated one, a revoked installation's included, and an enrolment once its body is readable | The installation id |
| `kf.allowance.row` | Every request from an active installation, and every enrolment that issued a credential | `evaluation`, `standard` or `enterprise`: the allowance row it was decided against |
| `kf.error.code` | Every refusal, and nothing else | The `X-KF-Error-Code` it was refused with |
| `kf.chat.tokens` | Every `/api/chat` that reached the provider, or tried to | What the provider says the turn cost; `0` when it never answered |
| `kf.chat.upstream` | The same | `ok`, or `failed`: refused, unreachable, too slow, or broken off mid-answer |
| `kf.enrolment` | Every enrolment that issued a credential | `new`, or `re_enrolment` for an installation that already existed |

And every quarter of an hour, one line in `traces` from `SpendReport`, whether or not anybody
called:

| Custom dimension | Holds |
|---|---|
| `Day` | Today, UTC, as `2026-09-27` |
| `TokensToday` | Every installation's tokens today so far, from the ledger |
| `TokensTrailingDailyMean` | Every installation's tokens over the seven whole days before today, divided by seven. An idle day counts as zero |

- **These names are the alerts.** A rule filters on exactly these strings, and one that matches
  nothing does not fire, and does not say so either. `SpanTagTests` and `SpendReportTests` spell
  them out rather than referencing the constants, so renaming one fails a test before it can
  silently disarm an alert. Renaming one means changing it here in the same change.
- **Metadata only** (invariant 2): an id, a word from a closed set, a count. `NoBodyLoggingTests`
  reads every one of them for its sentinels.
- **No source address**, anywhere. The address the gateway attributes a request to is shown to an
  operator on `GET /admin/status` and kept out of every sink, this one included. Where an address is
  needed, see *Ban a source address*.
- **Read access to this resource is a decision.** Dependency telemetry already carries the real
  upstream hostname (§B3). It now also carries every installation's id, and an id is all enrolment
  needs to rotate that installation's credential ([`API.md`](API.md): a nuisance the installation
  recovers from, not a disclosure). Grant it as narrowly as the admin token.

---

## The alerts

| Alert | Kind | Fires when | Severity |
|---|---|---|---|
| [Global brake tripped](#global-brake-tripped) | Log search | Any request refused `service_paused` in 5 minutes | 1 — Error |
| [Health check failing](#health-check-failing) | Metric, App Service | `/health` not answering `200` for 5 minutes | 1 — Error |
| [Upstream failures](#upstream-failures) | Log search | At least 3 chats in 15 minutes failed at the provider, and over a fifth of them | 2 — Warning |
| [Spend anomaly](#spend-anomaly) | Log search | Today has already spent 3 average days, and at least 1,000,000 tokens | 2 — Warning |
| [Telemetry silent](#telemetry-silent) | Log search | Nothing at all in Application Insights for an hour | 2 — Warning |
| [Second instance](#second-instance) | Metric, App Service plan | More than one instance running | 2 — Warning |
| [Database storage](#database-storage) | Metric, Flexible Server | Storage above 80% for an hour | 2 — Warning |
| [Enrolment spike](#enrolment-spike) | Log search | More than 10 new installations in an hour | 3 — Informational |

Every threshold is a **starting value** chosen before there was traffic to choose it from. Change
it in the rule, which needs no deploy, and change it here in the same breath: the next person to
read an alert reads this table.

Every log search rule is created on the Application Insights resource (so the table names above
resolve), measures **table rows** with aggregation **count**, and fires when the count is
**greater than 0** — each query returns a row only when something is wrong — except *Telemetry
silent*, which fires when it is **less than 1**. The look-back is the rule's *aggregation
granularity*. Where a query has a threshold it is a `let` at the top, so that tuning it, or lowering
it to prove the rule fires, is an edit to the query.

### Global brake tripped

**Watches:** the whole service is paused. Every chat and every other request on `/api` is refused
`503 service_paused`, for every installation, until an operator raises the ceiling.

```kusto
requests
| where tostring(customDimensions["kf.error.code"]) == "service_paused"
| summarize refused = count()
| where refused > 0
```

Evaluated every **5 minutes**, looking back **5 minutes**. It is quiet while nobody calls, even if
the brake is tripped: the brake is only ever discovered by a request.

**When it fires:**

1. Read `brake` on `GET /admin/status`. `used` against `ceiling` says how far past it the month is;
   `period_end` says when it clears by itself.
2. Decide whether the spend was honest. `GET /admin/usage/summary` for the month so far names the
   biggest spenders; if one or a handful of installations account for it, that is abuse, and
   *Abuse: one installation* comes first — releasing the brake with an abuser still admitted pauses
   the service again.
3. Release it: [`Admin.md`](Admin.md), *Release the global brake*. `tripped` on the next status read
   says it took, and the alert resolves on its own once no request has been refused for 5 minutes.

### Health check failing

**Watches:** App Service's own health check on `/health`. `/health` checks neither the database nor
the provider (§B1), so this is the process: it has not started, it has crashed, or it is failing
every request.

A metric alert on the **App Service** `app-stg-ai-gw`: *Health check status*, average, **less than
100**, over **5 minutes**, evaluated every **minute**.

**When it fires:**

1. The App Service's *Log stream*, and *Diagnose and solve problems*. A process
   that will not start writes why: an options validation failure names the setting
   (`Forwarding:*`, `Database:*`, `Admin:*`), and a failed migration names the migration.
2. A settings change is the usual cause, since saving one restarts the app. *Activity log* on the App
   Service says who changed what, and when.
3. A deploy is the other: *Deployment Center* for the last one, and `version` on `GET
   /admin/status` once it answers again.

### Upstream failures

**Watches:** the provider. A chat counts as failed when the provider refused it, could not be
reached, did not answer in time (`502 upstream_unavailable`, `504 upstream_timeout`), or broke off
after the answer began, which the client sees as a broken stream rather than a code.

```kusto
let minimum_failures = 3;
let failure_share = 0.2;
requests
| where isnotempty(customDimensions["kf.chat.upstream"])
| summarize chats = count(), failed = countif(tostring(customDimensions["kf.chat.upstream"]) == "failed")
| where failed >= minimum_failures and failed > failure_share * chats
```

Evaluated every **5 minutes**, looking back **15 minutes**.

**When it fires:**

1. Which failure? The gateway logs a warning per failed chat, naming the stage and never the host:
   ```kusto
   traces
   | where timestamp > ago(1h) and customDimensions.CategoryName == "KnowledgeFabric.AiGateway.Forwarding.ChatForwarder"
   | summarize count() by message
   ```
   `could not be reached` is the network or the address; `refused the request with 401` is the key;
   `with 429` is the provider's own cap (kf-app#817's provider-side limit, reached before ours);
   `timed out` is the provider being slow.
2. The provider's status page, and its dashboard for the account's usage and limits.
3. Nothing in the gateway fixes a provider outage, and nothing needs to: a chat that failed before
   its answer began was answered with its code and spent nothing, and the application tells its user.
   A key that has stopped working is a key rotation:
   [*A key that has stopped working*](#a-key-that-has-stopped-working).

### Spend anomaly

**Watches:** the whole service spending far more today than on an ordinary day of the week before —
a runaway, an abuser the per-installation limits did not contain, or an allowance raised too far.
Read from `SpendReport`'s line, which compares today with the trailing seven days from the daily
ledger, because a log search query cannot look back eight days and the ledger is the authority on
what a day cost.

```kusto
let ratio = 3.0;          // today so far, as a multiple of an average day
let floor = 1000000;      // tokens today below which nothing is worth waking anyone for
traces
| where isnotempty(customDimensions.TokensToday)
| top 1 by timestamp desc
| extend today = tolong(customDimensions.TokensToday), mean = tolong(customDimensions.TokensTrailingDailyMean)
| where today >= floor and today > ratio * mean
| project timestamp, day = tostring(customDimensions.Day), today, mean
```

Evaluated every **hour**, looking back **1 hour**, which always holds a report. Today is *so far*,
so a morning reading under-reports, never over-reports: the alert fires once today has already
spent three whole average days. The floor is what stops a first busy day after a quiet week from
paging anyone; while the trailing mean is small, it is the floor that decides.

**When it fires:**

1. Is it still climbing? `spend` on `GET /admin/status` is the same reading, read by the same code,
   current to the request rather than to the last quarter hour.
2. Who? `GET /admin/usage/summary?from=<today>&to=<today>` lists the biggest spenders today, by
   row. For the last hour rather than the day:
   ```kusto
   requests
   | where timestamp > ago(1h) and isnotempty(customDimensions["kf.chat.tokens"])
   | summarize tokens = sum(tolong(customDimensions["kf.chat.tokens"])), chats = count()
       by installation = tostring(customDimensions["kf.installation.id"]), row = tostring(customDimensions["kf.allowance.row"])
   | top 10 by tokens
   ```
3. One installation, or a few: *Abuse: one installation*. If it is within its allowance, the
   allowance is the problem — check its row, and any limits its licence sets over the row
   ([`Admin.md`](Admin.md), *An installation's allowance*).
4. Many small `evaluation` installations: that is minting, not use. See *Enrolment spike*.
5. How close is the brake? `brake.used` against `brake.ceiling` on `GET /admin/status`. The brake
   stops everyone; lowering one installation's allowance or revoking it stops only the cause.
6. Honest growth: raise the floor, and review the brake's ceiling against the new normal.

### Telemetry silent

**Watches:** Application Insights hearing nothing at all from the gateway. `SpendReport` writes a
line every quarter of an hour however quiet the service is, so an hour of nothing means the gateway
is not running, or cannot reach its sink — and while it lasts, **every log search alert above is
blind**, since each reads what the gateway sends.

```kusto
union requests, traces, dependencies, exceptions
```

Fires when the count of rows is **less than 1**, evaluated every **15 minutes**, looking back
**1 hour**.

**When it fires:**

1. Is it running? `GET /admin/status`. No answer is the *Health check failing* alert's territory,
   which should be firing too.
2. It answers: read `telemetry.configured`. `false` means `APPLICATIONINSIGHTS_CONNECTION_STRING` is
   missing from the App Service's settings (§B3, §B4). The gateway serves normally without it, which
   is exactly why this alert exists.
3. `true`, and still nothing arriving: the connection string points at a different resource, or the
   resource's ingestion is capped (*Usage and estimated costs → Daily cap*).

### Second instance

**Watches:** the App Service plan running more than one copy of the gateway. The request rate
limiter holds its window in process, so two instances each admit a full allowance: every rate limit
is doubled and `X-KF-Requests-Remaining` is a fiction, with nothing failing to say so (G6, §B1).

A metric alert on the App Service **plan**: *Instance Count*, maximum, **greater than 1**, over
**5 minutes**, evaluated every **minute**.

**When it fires:**

1. The plan's *Scale out* blade: set a manual count of **1**, and delete any autoscale rule there.
2. The plan's *Activity log* says who changed it. A platform move can briefly overlap two instances
   by itself; if nobody scaled it and it resolves within minutes, that is what it was.
3. Nothing needs cleaning up. The windows are exact again one window after the second instance goes,
   and the token budgets are in the database, where two instances count correctly.

### Database storage

**Watches:** the shared PostgreSQL Flexible Server filling up. It holds both databases, so this is
one alert for the server, not one per environment. A full server refuses writes: every chat's token
count, every enrolment and every ledger flush fails.

A metric alert on the **Flexible Server**: *Storage percent*, average, **greater than 80**, over
**1 hour**, evaluated every **15 minutes**.

**When it fires:**

1. Which database, and which table? From `psql` on the server:
   ```sql
   SELECT datname, pg_size_pretty(pg_database_size(datname)) FROM pg_database ORDER BY pg_database_size(datname) DESC;
   SELECT relname, pg_size_pretty(pg_total_relation_size(relid)) FROM pg_statio_user_tables ORDER BY pg_total_relation_size(relid) DESC;
   ```
2. The gateway's tables grow slowly by design: `DailyUsage` is about 100,000 rows a year for a few
   hundred installations, and `EnrolmentAttempts` is pruned as it is written. A table growing fast
   is a bug or an abuser, not load.
3. Otherwise, grow the storage: the server's *Compute + storage* blade. Storage can be raised and
   never lowered, so raise it by what the growth needs rather than generously. Where the blade offers
   *Storage autogrow*, turning it on removes this failure, at the price of this alert becoming a
   notice about the bill.

### Enrolment spike

**Watches:** installations being created faster than the product is being installed. Enrolment is
unauthenticated, and each new installation brings a fresh `evaluation` allowance, so someone
minting them turns the per-installation limits into a pool of their own. Only new installations
count: a credential rotated for an existing one is the application recovering from a `401`, and a
fleet doing that at once is not an attack.

```kusto
let threshold = 10;       // new installations in an hour
requests
| where tostring(customDimensions["kf.enrolment"]) == "new"
| summarize new_installations = count()
| where new_installations > threshold
```

Evaluated every **15 minutes**, looking back **1 hour**.

**When it fires:**

1. Are they real? A rollout at a customer is a burst of new installations that go on to chat
   normally. Look at what they do:
   ```kusto
   let minted = requests
       | where timestamp > ago(6h) and tostring(customDimensions["kf.enrolment"]) == "new"
       | distinct installation = tostring(customDimensions["kf.installation.id"]);
   requests
   | where timestamp > ago(6h) and isnotempty(customDimensions["kf.chat.tokens"])
   | extend installation = tostring(customDimensions["kf.installation.id"])
   | where installation in (minted)
   | summarize chats = count(), tokens = sum(tolong(customDimensions["kf.chat.tokens"])) by installation
   | order by tokens desc
   ```
   Many installations each spending close to their whole allowance quickly is minting.
2. Minting: arm the enrolment velocity limit ([`Admin.md`](Admin.md), *Arm the enrolment velocity
   limit*), **after** verifying the address it would count, as that section says. It limits each
   source address, and from then on records the addresses enrolling.
3. Revoke the minted installations that are spending ([`Admin.md`](Admin.md), the revoke
   endpoint), biggest first. Revocation survives re-enrolment.
4. One address keeps coming back: *Ban a source address*.

---

## Procedures

### Abuse: one installation

1. Find it: the biggest spenders from `GET /admin/usage/summary`, or the last hour's from the query
   under *Spend anomaly*. Its refusals say what it is running into:
   ```kusto
   requests
   | where timestamp > ago(1h) and tostring(customDimensions["kf.installation.id"]) == "<installation id>"
   | summarize count() by code = tostring(customDimensions["kf.error.code"]), bin(timestamp, 5m)
   | render timechart
   ```
   A steady stream of `rate_limited` and `token_budget_exhausted` is an installation the limits are
   already containing: each of those was refused before the provider was asked, so it costs nothing
   but its own requests.
2. Read it: `GET /admin/installations/<id>` — its row, its licence, what it is allowed and has used.
   A licensed installation is a customer: talk to them before anything else.
3. Stop it: `POST /admin/installations/<id>/revoke`, with `X-KF-Operator` naming you. Every call it
   makes from then on is `403 installation_revoked`, including with a credential it re-enrols for.
   `restore` undoes it.
4. If it is an allowance that is too generous rather than an installation misbehaving, move the
   allowance instead: [`Admin.md`](Admin.md), *Move a tier's allowance*.

The revoked installation stays named on its refusals, so it is easy to see whether it is still
trying:

```kusto
requests
| where timestamp > ago(1d) and tostring(customDimensions["kf.error.code"]) == "installation_revoked"
| summarize count() by installation = tostring(customDimensions["kf.installation.id"])
```

### Ban a source address

For one address that keeps enrolling or calling after revocation and the velocity limit. It is a
platform setting, not policy: **App Service → Networking → Access restrictions**, on the App
Service `app-stg-ai-gw`.

1. Find the address. The gateway does not put addresses in telemetry. With the enrolment velocity
   limit armed, `EnrolmentAttempts` holds the addresses enrolling, from `psql`:
   ```sql
   SELECT "SourceAddress", count(*) FROM "EnrolmentAttempts" GROUP BY 1 ORDER BY 2 DESC LIMIT 10;
   ```
2. Add a **Deny** rule for that address alone, and leave **Unmatched rule action** on **Allow**.
   Turning the unmatched action to deny makes it an allow-list, and refuses every installation in the
   world.
3. The address is refused `403` by the platform, before the gateway sees it. That answer carries no
   `X-KF-Error-Code`, so the application treats it as a failure it does not recognise rather than as
   a revocation. For the one address it is meant for, that is fine.

A rule is a change to the App Service's configuration, recorded in its *Activity log* rather than
in the gateway's audit lines. Remove it when it has done its job: addresses change hands.

### Change tier policy

[`Admin.md`](Admin.md), *Policy*: read the rows, change one with a `PUT`, and the audit line it
leaves. *Move a tier's allowance* and *Raise a licence tier's allowance* cover the usual reasons.
After a change, the query under *Abuse: one installation*, run against a few installations on that
row, shows their refusals move.

### Retire an application generation

The minimum-version lever: [`Admin.md`](Admin.md), *Retire an application generation*, and
`?app_version_below=` on the list first, to see who it would refuse before it refuses them. Once it
is set, the installations still trying to enrol with an older version are named on their refusals:

```kusto
requests
| where timestamp > ago(7d) and tostring(customDimensions["kf.error.code"]) == "app_version_unsupported"
| summarize attempts = count(), last = max(timestamp) by installation = tostring(customDimensions["kf.installation.id"])
```

This is the **application's** public image being retired. The gateway has no image of its own.

### Release the global brake

[`Admin.md`](Admin.md), *Release the global brake*, after *Global brake tripped* above.

### Rotate the provider key

The key is in two places: the App Service setting `AI_GATEWAY_OLLAMA_API_KEY` on `app-stg-ai-gw`
([`Provisioning-Environments.md`](Provisioning-Environments.md) §B4), and the provider account's list
of keys. It is not in the repository, not in GitHub, not in a CI log, and not in a password manager
(invariant 1). Rotating it changes those two places and nothing else, and **no copy is kept**: if a key
is needed again, mint a new one.

Nothing in the gateway records a rotation. The App Service's *Activity log* records who changed the
setting and when, and the provider's account records who minted or revoked a key.

Three situations, three orders:

- **[Planned rotation](#planned-rotation)**: the new key goes in first and the old one is revoked
  last, so the only outage is the restart. Use it when someone who could read the setting or the
  provider account leaves, when the provider asks, or on a suspicion with no sign the key was used.
- **[A leaked key](#a-leaked-key)**: the old key is revoked first, and the outage is accepted.
- **[A key that has stopped working](#a-key-that-has-stopped-working)**: *Upstream failures* fired
  with `refused the request with 401`, and nobody rotated anything.

#### What the restart costs

Saving the setting restarts the app. There is no slot to swap yet
([#17](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/17)), so the restart is the outage. We
accept it by choice, and choose when:

- **Every stream in flight is dropped.** The application sees a broken stream, not a code.
- **Requests that arrive while the new process starts are handled by the platform.** They wait, or
  the platform answers them, and the platform's answer has no `X-KF-Error-Code`.
- **Every request window starts again.** `X-KF-Requests-Remaining` goes back to full, so a few
  requests too many may be admitted for one window (§B1). Token budgets and the brake are kept in the
  database, so a restart neither refills a budget nor releases the brake.
- **The usage ledger loses nothing.** The process writes what it holds as it shuts down
  ([`Admin.md`](Admin.md), *Usage history*).

For a planned rotation, pick a quiet hour. The requests show which hours are quiet:

```kusto
requests
| where timestamp > ago(7d) and isnotempty(customDimensions["kf.chat.upstream"])
| summarize chats = count() by hour_utc = hourofday(timestamp)
| order by chats asc
```

#### Before you start

You need access to the App Service's *Environment variables* in the Portal, access to the provider
account's API keys, and Application Insights `app-stg-ai-gw` → *Logs* open. You also need a shell
with these definitions, which chat as a test installation of your own:

```bash
GW=https://ai.knowledgefabric.io
TOKEN=…            # Admin__ReadToken is enough. Nothing here needs the provider key.
INSTALLATION=…     # your own test installation's id; the first time, $(uuidgen | tr 'A-Z' 'a-z')
status() { curl -s -H "Authorization: Bearer $TOKEN" "$GW/admin/status" | jq -c '{version, started_at}'; }
enrol() { CRED=$(curl -s -X POST "$GW/v1/installations" -H 'Content-Type: application/json' \
  -d "{\"installation_id\":\"$INSTALLATION\",\"app_version\":\"1.6.2\",\"licence\":null}" | jq -r .credential)
  echo "${CRED:0:4}"; }
chat() { curl -s -o /dev/null -w '%{http_code} %header{x-kf-error-code}\n' -X POST "$GW/api/chat" \
  -H "Authorization: Bearer $CRED" -H 'Content-Type: application/json' \
  -d '{"model":"knowledge-fabric-ai","stream":false,"messages":[{"role":"user","content":"Say hello."}]}'; }
```

Use the same installation id each time. Enrolling it again gives it a fresh credential, so the fleet
gains one test installation in total, not one per rotation. `enrol` prints `kfg_`, the start of the
credential. If it prints `null`, enrolment refused the request: `426 app_version_unsupported` means the
minimum version is above `1.6.2`, and `429 enrolment_rate_limited` means the velocity limit is
counting your address. Neither has anything to do with the key.

**Only `/api/chat` tests the key.** `/api/tags` and `/api/show` answer `200` whatever the key is,
because the gateway answers them itself from the alias and never asks the provider.

#### Planned rotation

1. **Record the starting state.** Run `status` and note `started_at`. Run `enrol` (→ `kfg_`), then
   `chat` → `200`. The current key works, so if a chat fails later, the new key is the cause.
2. **Mint the new key** in the provider account. Name it after today's date, so that step 6 can tell
   the two keys apart. Keep the page that shows it open until step 5 passes: if the provider shows a
   key only once, a paste that did not take can be fixed from that page, without minting a third key.
   Copy the key from that page straight into the Portal. Do not put it in a file, a note, a chat or a
   ticket. Do not test it with `curl` first, because that writes it into a shell history. The gateway
   is the test.
3. **Paste it.** In the App Service `app-stg-ai-gw`, go to *Settings → Environment variables → App
   settings* and open `AI_GATEWAY_OLLAMA_API_KEY`. Replace the value with the key and nothing else: the
   gateway does not trim the value, so a stray space is sent as part of the key. Leave
   *Deployment slot setting* unticked (see [Once there is a slot](#once-there-is-a-slot)). Select
   *Apply* in the pane, then *Apply* at the foot of the blade, then **confirm**. If you skip the
   confirmation, nothing restarts and the old key stays in force. Edit this one setting, not *Advanced
   edit*: that view shows the value of every setting at once, the connection string and the admin
   tokens included.
4. **Wait for the restart.** Repeat `curl -s -o /dev/null -w '%{http_code}\n' $GW/health` until it
   prints `200`. Then run `status`: `started_at` must be later than it was in step 1. **If it has not
   changed, the setting was not applied.** The process answering still holds the old key, and every
   check below would pass on the old key. Go back to step 3.
5. **Check the new key.** `chat` → `200`, using the credential from step 1, which a restart does not
   change. Wait a few minutes, because telemetry takes that long to reach the workspace. Then run this
   query:
   ```kusto
   let restarted = datetime(2026-09-27T10:00:00Z);   // started_at from step 4
   traces
   | where timestamp > restarted and customDimensions.CategoryName == "KnowledgeFabric.AiGateway.Forwarding.ChatForwarder"
   | where tostring(customDimensions.UpstreamStatus) == "401"
   | count
   ```
   The result must be `0`. If `chat` answered `502 upstream_unavailable` and the query found a row, the
   provider refused the new key: go back to step 3 and paste it again from step 2's page. If that page
   is closed, mint another key, paste that one, and revoke the key that failed. A `502` or `504`
   with no `401` row is not the key: see [Upstream failures](#upstream-failures), step 1.
6. **Revoke the old key** at the provider: the one not named for today. Allow a few minutes for the
   revocation to take effect at the provider.
7. **Check again.** `chat` → `200`, then run step 5's query again → `0`. **This check proves the
   rotation**: with the old key revoked, a `200` can only come from the new key. *Upstream failures*
   stays quiet throughout. If it fired, the cause was a failure at step 5, and the alert resolves by
   itself once 15 minutes pass with no failures.
8. Close the provider's page. There is nothing else to write down.

#### A leaked key

Use this when the key has been seen anywhere other than the setting and the provider's own page: a
commit, a CI log, a ticket, a chat, a screen share, a terminal. Also use it when the provider reports
spend that the ledger does not account for.

1. **Revoke the key at the provider, now.** The outage starts here. From now on every chat is `502
   upstream_unavailable`, and each one logs `The provider refused the request with 401.`. Accept it.
   The limits and the brake count only what passes through the gateway. Whoever holds the key spends
   the account directly, and nothing of ours sees it or stops it.
2. **Put a new key in** with *Planned rotation* steps 1 to 5. Step 1's `chat` now answers `502`, but
   `enrol` still works, because enrolment never asks the provider. The outage ends at step 5's `200`.
   *Upstream failures* fires once three chats have failed within 15 minutes. That is expected, and it
   resolves by itself.
3. **Find out what the leak cost.** Compare the provider's usage figures for the days since the leak
   could have happened with the gateway's own figures for the same days. For the gateway's figures,
   `GET /admin/usage/summary?from=<first day>&to=<today>` → `totals.tokens`. Nothing but the gateway
   should use the account, so the difference is what someone else spent with the key.
4. **Find where it leaked from.** The people who could have read the key are:
   - **Anyone with a role on the App Service that can list its settings.** The App Service's *Access
     control (IAM)* blade shows who. That includes the deploy's app registration, which holds *Website
     Contributor* there (§B5 step 4). The workflow never asks for the settings, but the role would
     allow it. The *Activity log* shows who listed or changed the settings, and when.
   - **The members of the provider account.**

   If the key turned up in a commit, a CI log or a ticket, it is revoked now and no longer works. The
   place it turned up is still a breach of invariant 1: record it on the epic
   ([kf-app#954](https://github.com/KnowledgeFabric/kf-app/issues/954)) so that the gap gets closed
   as well as the key replaced.

#### A key that has stopped working

This is *Upstream failures* with `refused the request with 401` when nobody rotated anything. There
are two possible causes. The App Service's *Activity log* shows which one it is:

- **The setting changed.** Someone saved it blank, or with a stray character. A blank setting does
  not stop the process from starting: an absent key is valid, because a local Ollama needs none. So the
  gateway starts, sends no key, and the provider refuses every chat with `401`. Fix it with the whole
  of *Planned rotation*, with a new key; step 1's `chat` answers `502` until step 5. We keep no copy
  of the old key, and step 6 revokes it, because nothing holds it any more.
- **The setting did not change.** The key was revoked, or expired, at the provider. Someone has done
  step 1 of *A leaked key* already, possibly the provider itself. Treat it as a leak until the
  provider account's history says otherwise, and continue from step 2 of *A leaked key*.

#### Once there is a slot

None of this applies today: there is no slot until #17. Once a `staging` slot exists:

- **The new key goes on `staging` only.** `staging` restarts, but no traffic reaches it. Run *Planned
  rotation* steps 4 and 5 against the slot's own default domain, from its *Overview*, as `GW`. That
  proves the new key before any installation uses it. The slot shares the one database, so the test
  installation and its spend are real rows either way.
- **Then swap `staging` into production.** Traffic moves to a process that is already running and
  already proven with the new key. What the swap does to streams in flight on the old process is for
  #17 to find out, by doing it.
- **The key must not be a *deployment slot setting*.** A slot setting stays with its slot when slots
  swap, so the swap would move the code and leave the old key behind. Leaving the setting unticked is
  what lets the swap carry the new key.
- **After the swap, `staging` holds the old key.** It is running the process that was serving
  traffic. Put the new key on `staging` as well before you revoke the old one. Otherwise the next swap
  carries a revoked key into production, whether that swap is the next deploy or a swap back to undo
  this one.
- **A swap still starts every request window again**, because a different process is now serving
  (§B1).
- **A leaked key is still revoked first.** The slot changes only how the new key goes in.

No swap has been done yet, so this part was written without one. #17's *Done when* asks for it to be
rewritten once a swap has been done.

### Restore the database

This procedure is not written here: it belongs to
[#16](https://github.com/KnowledgeFabric/kf-ai-gateway/issues/16). After a restore, see
[`Admin.md`](Admin.md), *After a restore*.

---

## Useful queries

The figures G8 names, for a chart or a question. Per installation per day, and anything older than
30 days, the ledger answers better: `GET /admin/usage/daily`.

```kusto
// Enrolments per hour, new against re-enrolments.
requests
| where timestamp > ago(7d) and isnotempty(customDimensions["kf.enrolment"])
| summarize count() by kind = tostring(customDimensions["kf.enrolment"]), bin(timestamp, 1h)
| render timechart

// Tokens per installation per day.
requests
| where timestamp > ago(7d) and isnotempty(customDimensions["kf.chat.tokens"])
| summarize tokens = sum(tolong(customDimensions["kf.chat.tokens"]))
    by installation = tostring(customDimensions["kf.installation.id"]), day = startofday(timestamp)
| order by day desc, tokens desc

// Refusals by code, per hour.
requests
| where timestamp > ago(1d) and isnotempty(customDimensions["kf.error.code"])
| summarize count() by code = tostring(customDimensions["kf.error.code"]), bin(timestamp, 1h)
| render timechart

// The 429 rate: the share of requests from installations refused 429, per hour.
requests
| where timestamp > ago(7d) and isnotempty(customDimensions["kf.installation.id"])
| summarize requests = count(), refused_429 = countif(resultCode == "429") by bin(timestamp, 1h)
| extend rate_429 = todouble(refused_429) / requests
| render timechart

// The upstream error rate, per hour.
requests
| where timestamp > ago(7d) and isnotempty(customDimensions["kf.chat.upstream"])
| summarize chats = count(), failed = countif(tostring(customDimensions["kf.chat.upstream"]) == "failed") by bin(timestamp, 1h)
| extend failure_rate = todouble(failed) / chats
| render timechart

// Spend per day: the last report of each day. Multiply by the provider's price per token for money;
// the gateway holds no price, because it is the provider's and changes without a deploy of ours.
traces
| where timestamp > ago(30d) and isnotempty(customDimensions.TokensToday)
| summarize arg_max(timestamp, customDimensions) by day = tostring(customDimensions.Day)
| project day, tokens = tolong(customDimensions.TokensToday)
| order by day asc
```
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminAllowance.cs">
public static AdminLicenceLimits Of(LicenceLimits limits) => new(
⋮----
limits.BudgetPeriod is { } period ? LicenceLimits.Periods.Of(period) : null,
⋮----
public static class RowWords
⋮----
public static string Of(PolicyTier row) => row.ToString().ToLowerInvariant();
⋮----
public static bool TryParse(string word, out PolicyTier row)
⋮----
if (string.Equals(Of(candidate), word, StringComparison.OrdinalIgnoreCase))
⋮----
public sealed class AdminAllowances(PolicyStore policies, RequestWindows windows, TimeProvider clock)
⋮----
public async Task<AdminAllowance> OfAsync(Installation installation, CancellationToken cancellationToken)
⋮----
var now = _now ??= clock.GetUtcNow();
var row = PolicyStore.RowFor(installation);
⋮----
if (!_rows.TryGetValue(row, out var policy))
⋮----
_rows[row] = policy = await policies.RowAsync(row, cancellationToken);
⋮----
var served = PolicyStore.Serve(installation, policy);
var quota = QuotaState.Of(QuotaSnapshot.Of(installation, served, windows.Peek(installation.Id, served, now), now));
⋮----
return new AdminAllowance(
RowWords.Of(row),
⋮----
AdminLicenceLimits.Of(PolicyStore.LicenceLimitsFor(installation)));
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminAudit.cs">
public static class AdminOperator
⋮----
public static bool TryRead(
⋮----
error = AdminFieldError.InvalidHeader(Header, $"{Header} is given more than once.");
⋮----
var value = values.ToString().Trim();
⋮----
if (value.Length > MaximumLength || value.Any(char.IsControl))
⋮----
error = AdminFieldError.InvalidHeader(
⋮----
public sealed class AdminAudit(ILogger<AdminAudit> logger, IOptions<HttpJsonOptions> json)
⋮----
public static class Actions
⋮----
public void Wrote(HttpContext http, string action, string target, string operatorName, object before, object after) =>
logger.LogInformation(
⋮----
JsonSerializer.Serialize(before, json.Value.SerializerOptions),
JsonSerializer.Serialize(after, json.Value.SerializerOptions));
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminBody.cs">
public static readonly AdminFieldError NotAnObject = new("invalid_body", null, "The body must be a JSON object.");
⋮----
public static AdminFieldError Unknown(string field, IEnumerable<string> known) =>
new("unknown_field", field, $"{field} is not a field of this row. It takes {string.Join(", ", known)}.");
⋮----
public static AdminFieldError Invalid(string field, string message) => new("invalid_field", field, message);
⋮----
public static AdminFieldError InvalidHeader(string header, string message) => new("invalid_header", header, message);
⋮----
public sealed class AdminBody
⋮----
public static async Task<(AdminBody? Body, AdminFieldError? Error)> ReadAsync(
⋮----
JsonDocument document;
⋮----
document = await JsonDocument.ParseAsync(request.Body, cancellationToken: cancellationToken);
⋮----
foreach (var property in document.RootElement.EnumerateObject())
⋮----
if (readOnly.FirstOrDefault(pair => string.Equals(pair.Key, property.Name, StringComparison.OrdinalIgnoreCase)) is { Key: not null } fixedField)
⋮----
return (null, AdminFieldError.Invalid(fixedField.Key, fixedField.Value));
⋮----
if (fields.FirstOrDefault(field => string.Equals(field, property.Name, StringComparison.OrdinalIgnoreCase)) is not { } field)
⋮----
return (null, AdminFieldError.Unknown(property.Name, fields));
⋮----
if (!given.TryAdd(field, property.Value.Clone()))
⋮----
return (null, AdminFieldError.Invalid(field, $"{field} is given more than once."));
⋮----
if (fields.FirstOrDefault(field => !given.ContainsKey(field)) is { } missing)
⋮----
return (null, AdminFieldError.Invalid(
⋮----
return (new AdminBody(given), null);
⋮----
public bool TryWhole(
⋮----
&& element.TryGetInt64(out var number)
⋮----
? $"at least {minimum.ToString(CultureInfo.InvariantCulture)}"
: $"from {minimum.ToString(CultureInfo.InvariantCulture)} to {maximum.ToString(CultureInfo.InvariantCulture)}";
⋮----
error = AdminFieldError.Invalid(
⋮----
public bool TryText(string field, [NotNullWhen(true)] out string? value)
⋮----
value = element.ValueKind == JsonValueKind.String ? element.GetString() : null;
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminEndpoints.cs">
public static AdminInstallation Of(AdminRow row, AdminAllowance allowance) => new(
⋮----
TierWords.Of(row.Installation.Tier),
⋮----
LicenceState.Of(row.Installation),
⋮----
public static async Task<AdminInstallation> OfAsync(
⋮----
Of(row, await allowances.OfAsync(row.Installation, cancellationToken));
⋮----
public sealed class AdminRow
⋮----
public static class AdminEndpoints
⋮----
public static void MapAdmin(this WebApplication app)
⋮----
app.Logger.LogWarning(
⋮----
app.Logger.LogInformation("No admin token is configured; the admin endpoints are not mapped.");
⋮----
var admin = app.MapGroup("/admin")
⋮----
.WithMetadata(NotInstallationAuthenticated.Instance);
⋮----
admin.MapGet("/status", AdminStatusEndpoint.Of(app).ReadAsync);
admin.MapGet("/installations", ListAsync);
admin.MapGet("/installations/{id:guid}", OneAsync);
admin.MapPost("/installations/{id:guid}/revoke", RevokeAsync);
admin.MapPost("/installations/{id:guid}/restore", RestoreAsync);
⋮----
admin.MapGet("/policy", ReadPolicyAsync);
admin.MapPut("/policy", WritePolicyAsync);
admin.MapGet("/tiers", ReadTiersAsync);
admin.MapPut("/tiers/{tier}", WriteTierAsync);
⋮----
admin.MapGet("/usage/daily", AdminUsageEndpoints.DailyAsync);
admin.MapGet("/usage/summary", AdminUsageEndpoints.SummaryAsync);
⋮----
private static async Task<IResult> ListAsync(
⋮----
if (!InstallationQuery.TryParse(http.Request.Query, out var query, out var error))
⋮----
return Results.BadRequest(error);
⋮----
var total = await rows.CountAsync(cancellationToken);
⋮----
http.Response.Headers["X-Total-Count"] = total.ToString(CultureInfo.InvariantCulture);
⋮----
return Results.Ok(page);
⋮----
private static async Task<List<AdminInstallation>> InDatabaseOrderAsync(
⋮----
? rows.OrderByDescending(row => row.Installation.LastSeenAt).ThenByDescending(row => row.Installation.CreatedAt)
: rows.OrderByDescending(row => row.Installation.CreatedAt);
⋮----
IQueryable<AdminRow> paged = ordered.ThenBy(row => row.Installation.Id).Skip(query.Offset);
⋮----
paged = paged.Take(limit);
⋮----
foreach (var row in await paged.ToListAsync(cancellationToken))
⋮----
page.Add(await AdminInstallation.OfAsync(row, allowances, cancellationToken));
⋮----
private static async Task<List<AdminInstallation>> ByTokensUsedAsync(
⋮----
foreach (var row in await rows.ToListAsync(cancellationToken))
⋮----
all.Add(await AdminInstallation.OfAsync(row, allowances, cancellationToken));
⋮----
.OrderByDescending(installation => installation.Allowance.Tokens.Used)
.ThenByDescending(installation => installation.CreatedAt)
.ThenBy(installation => installation.InstallationId)
.Skip(query.Offset);
⋮----
return [.. query.Limit is { } limit ? ordered.Take(limit) : ordered];
⋮----
private static async Task<IQueryable<AdminRow>> FilteredAsync(
⋮----
var installations = database.Installations.AsNoTracking();
⋮----
installations = installations.Where(row => row.LicenceId == id);
⋮----
installations = installations.Where(PolicyStore.OnRow(served));
⋮----
? installations.Where(row => row.RevokedAt != null)
: installations.Where(row => row.RevokedAt == null);
⋮----
installations = installations.Where(row => row.LastSeenAt >= since);
⋮----
.Select(row => row.AppVersion)
.Distinct()
.ToListAsync(cancellationToken);
⋮----
var below = versions.Where(version => !AppVersions.IsAtLeast(version, minimum)).ToList();
⋮----
installations = installations.Where(row => below.Contains(row.AppVersion));
⋮----
rows = rows.Where(row => row.LicenceHolders > 1);
⋮----
private static async Task<IResult> OneAsync(
⋮----
var row = await Rows(database).SingleOrDefaultAsync(row => row.Installation.Id == id, cancellationToken);
⋮----
? Results.NotFound()
: Results.Ok(await AdminInstallation.OfAsync(row, allowances, cancellationToken));
⋮----
private static Task<IResult> RevokeAsync(
⋮----
installation => installation.RevokedAt ??= clock.GetUtcNow());
⋮----
private static Task<IResult> RestoreAsync(
⋮----
private static async Task<IResult> UpdateAsync(
⋮----
if (!AdminOperator.TryRead(http.Request, out var operatorName, out var refused))
⋮----
return Results.BadRequest(refused);
⋮----
var installation = await database.Installations.FirstOrDefaultAsync(row => row.Id == id, cancellationToken);
⋮----
return Results.NotFound();
⋮----
var before = AdminRevocation.Of(installation);
⋮----
await database.SaveChangesAsync(cancellationToken);
⋮----
audit.Wrote(http, action, id.ToString(), operatorName, before, AdminRevocation.Of(installation));
⋮----
var listed = await Rows(database).SingleAsync(row => row.Installation.Id == id, cancellationToken);
⋮----
return Results.Ok(await AdminInstallation.OfAsync(listed, allowances, cancellationToken));
⋮----
private static async Task<IResult> ReadPolicyAsync(PolicyStore policies, CancellationToken cancellationToken) =>
Results.Ok(AdminGatewayPolicy.Of(await policies.GatewayAsync(cancellationToken)));
⋮----
private static async Task<IResult> WritePolicyAsync(
⋮----
var (body, error) = await AdminBody.ReadAsync(
⋮----
if (body is null || !AdminGatewayPolicy.TryRead(body, out var policy, out error))
⋮----
var row = await database.GatewayPolicy.SingleAsync(cancellationToken);
var before = AdminGatewayPolicy.Of(row);
⋮----
policy.WriteTo(row);
⋮----
var written = AdminGatewayPolicy.Of(row);
audit.Wrote(http, AdminAudit.Actions.Policy, AdminAudit.GatewayTarget, operatorName, before, written);
⋮----
return Results.Ok(written);
⋮----
private static async Task<IResult> ReadTiersAsync(
⋮----
tiers.Add(AdminTier.Of(await policies.RowAsync(row, cancellationToken), served[RowWords.Of(row)]));
⋮----
return Results.Ok(tiers);
⋮----
private static async Task<IResult> WriteTierAsync(
⋮----
if (!RowWords.TryParse(tier, out var named))
⋮----
if (body is null || !AdminTierLevers.TryRead(body, out var levers, out error))
⋮----
var row = await database.TierPolicies.SingleAsync(policy => policy.Tier == named, cancellationToken);
var before = AdminTierLevers.Of(row);
⋮----
levers.WriteTo(row);
⋮----
audit.Wrote(http, AdminAudit.Actions.Tier, RowWords.Of(named), operatorName, before, AdminTierLevers.Of(row));
⋮----
return Results.Ok(AdminTier.Of(row, served[RowWords.Of(named)]));
⋮----
private static async Task<IReadOnlyDictionary<string, int>> ServedAsync(
⋮----
(await AdminFleet.CountAsync(database, clock.GetUtcNow(), cancellationToken)).ByRow;
⋮----
private static IQueryable<AdminRow> Rows(GatewayDbContext database) =>
Rows(database, database.Installations.AsNoTracking());
⋮----
private static IQueryable<AdminRow> Rows(GatewayDbContext database, IQueryable<Installation> installations) =>
⋮----
.Select(row => new AdminRow
⋮----
LicenceHolders = database.Installations.Count(other =>
⋮----
public sealed class AdminTokenFilter(IOptions<AdminOptions> options) : IEndpointFilter
⋮----
private readonly byte[] _token = Encoding.UTF8.GetBytes(options.Value.Token!);
⋮----
? Encoding.UTF8.GetBytes(options.Value.ReadToken!)
⋮----
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
⋮----
var header = request.Headers.Authorization.ToString();
⋮----
var presented = header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
? Encoding.UTF8.GetBytes(header["Bearer ".Length..].Trim())
⋮----
if (CryptographicOperations.FixedTimeEquals(presented, _token))
⋮----
if (_readToken is not null && CryptographicOperations.FixedTimeEquals(presented, _readToken))
⋮----
return HttpMethods.IsGet(request.Method) || HttpMethods.IsHead(request.Method)
⋮----
: Results.StatusCode(StatusCodes.Status403Forbidden);
⋮----
return Results.Unauthorized();
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminOptions.cs">
public sealed class AdminOptions
⋮----
public bool IsConfigured => !string.IsNullOrWhiteSpace(Token);
⋮----
public bool HasReadToken => !string.IsNullOrWhiteSpace(ReadToken);
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminPolicy.cs">
public static AdminGatewayPolicy Of(GatewayPolicy row) =>
⋮----
public void WriteTo(GatewayPolicy row)
⋮----
public static bool TryRead(
⋮----
if (!body.TryText("minimum_app_version", out var version) || !AppVersions.IsVersion(version))
⋮----
error = AdminFieldError.Invalid("minimum_app_version", "minimum_app_version must be a version, such as 1.7.0.");
⋮----
version = version.Trim();
⋮----
error = AdminFieldError.Invalid(
⋮----
if (!body.TryWhole("enrolments_per_hour", 1, int.MaxValue, nullable: true, out var perHour, out error)
|| !body.TryWhole("enrolments_per_day", 1, int.MaxValue, nullable: true, out var perDay, out error)
|| !body.TryWhole("global_token_ceiling", 1, long.MaxValue, nullable: true, out var ceiling, out error))
⋮----
policy = new AdminGatewayPolicy(version, (int?)perHour, (int?)perDay, ceiling);
⋮----
public static AdminTierLevers Of(TierPolicy row) => new(
⋮----
BudgetPeriodWords.Of(row.BudgetPeriod),
⋮----
public void WriteTo(TierPolicy row)
⋮----
row.RequestWindow = TimeSpan.FromSeconds(RequestWindowSeconds);
⋮----
row.BudgetPeriod = BudgetPeriodWords.Parse(BudgetPeriod);
⋮----
if (!body.TryWhole("requests_per_window", 1, int.MaxValue, nullable: false, out var requests, out error)
|| !body.TryWhole("request_window_seconds", 1, int.MaxValue, nullable: false, out var window, out error)
|| !body.TryWhole("token_budget", 1, long.MaxValue, nullable: false, out var budget, out error))
⋮----
if (!body.TryText("budget_period", out var period) || !BudgetPeriodWords.TryParse(period, out _))
⋮----
if (!body.TryWhole("max_predict_tokens", 1, int.MaxValue, nullable: false, out var maxPredict, out error))
⋮----
levers = new AdminTierLevers((int)requests!, window!.Value, budget!.Value, period, (int)maxPredict!);
⋮----
public static AdminTier Of(TierPolicy row, int installationsServed)
⋮----
var levers = AdminTierLevers.Of(row);
⋮----
return new AdminTier(
RowWords.Of(row.Tier),
⋮----
public static AdminRevocation Of(Installation installation) =>
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminServiceCollectionExtensions.cs">
public static class AdminServiceCollectionExtensions
⋮----
public static IServiceCollection AddAdmin(this IServiceCollection services, IConfiguration configuration)
⋮----
.Bind(configuration.GetSection(AdminOptions.SectionName))
.ValidateDataAnnotations()
.Validate(
options => options.ReadToken is null || !string.Equals(options.ReadToken, options.Token, StringComparison.Ordinal),
⋮----
.ValidateOnStart();
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminStatus.cs">
public static AdminBrake Of(BrakeState state) =>
⋮----
public static AdminSpend Of(SpendReading reading) =>
⋮----
public static async Task<AdminFleet> CountAsync(GatewayDbContext database, DateTimeOffset now, CancellationToken cancellationToken)
⋮----
var day = now.AddDays(-1);
var week = now.AddDays(-7);
var month = now.AddDays(-30);
⋮----
.GroupBy(row => new { row.Tier, row.LicenceTier, Revoked = row.RevokedAt != null })
.Select(group => new
⋮----
Count = group.Count(),
SeenLastDay = group.Count(row => row.LastSeenAt > day),
SeenLastWeek = group.Count(row => row.LastSeenAt > week),
SeenLastMonth = group.Count(row => row.LastSeenAt > month),
⋮----
.ToListAsync(cancellationToken);
⋮----
var active = groups.Where(group => !group.Revoked).ToList();
⋮----
return new AdminFleet(
Total: groups.Sum(group => group.Count),
Active: active.Sum(group => group.Count),
Revoked: groups.Where(group => group.Revoked).Sum(group => group.Count),
ByRow: Enum.GetValues<PolicyTier>().ToDictionary(
⋮----
row => active.Where(group => PolicyStore.RowFor(group.Tier, group.LicenceTier) == row).Sum(group => group.Count)),
SeenLastDay: active.Sum(group => group.SeenLastDay),
SeenLastWeek: active.Sum(group => group.SeenLastWeek),
SeenLastMonth: active.Sum(group => group.SeenLastMonth),
⋮----
.Where(group => group.Tier == Tier.Licensed && group.LicenceTier == null)
.Sum(group => group.Count));
⋮----
public static readonly AdminStatusError DatabaseUnreachable = new("database_unreachable");
⋮----
public sealed class AdminStatusEndpoint(string version, DateTimeOffset startedAt, bool telemetryConfigured)
⋮----
public static readonly TimeSpan ReadDeadline = TimeSpan.FromSeconds(3);
⋮----
public static AdminStatusEndpoint Of(WebApplication app) => new(
⋮----
app.Services.GetRequiredService<TimeProvider>().GetUtcNow(),
TelemetryServiceCollectionExtensions.HasSink(app.Configuration));
⋮----
public async Task<IResult> ReadAsync(
⋮----
var now = clock.GetUtcNow();
⋮----
BrakeState state;
AdminFleet fleet;
SpendReading spend;
⋮----
(state, fleet, spend) = await reading.WaitAsync(ReadDeadline, http.RequestAborted);
⋮----
logger.LogWarning(exception, "The status could not read the database; it answered 503 database_unreachable.");
⋮----
return Results.Json(AdminStatusError.DatabaseUnreachable, statusCode: StatusCodes.Status503ServiceUnavailable);
⋮----
return Results.Ok(new AdminStatus(
⋮----
new AdminTelemetry(telemetryConfigured),
AdminBrake.Of(state),
AdminSpend.Of(spend),
⋮----
new AdminCaller(ClientAddress.Of(http))));
⋮----
private static async Task<(BrakeState, AdminFleet, SpendReading)> ReadDatabaseAsync(
⋮----
using var deadline = CancellationTokenSource.CreateLinkedTokenSource(request);
deadline.CancelAfter(ReadDeadline);
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
var state = await services.GetRequiredService<GlobalBrake>().ReadAsync(now, deadline.Token);
var fleet = await AdminFleet.CountAsync(database, now, deadline.Token);
var spend = await SpendReport.ReadAsync(database, now, deadline.Token);
⋮----
private static bool Unreadable(Exception exception, CancellationToken request)
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/AdminUsage.cs">
public static AdminUsageDay Of(DateOnly day, UsageCounts counts, IReadOnlyDictionary<string, UsageCounts>? byRow = null) =>
⋮----
public static AdminUsageTotals Of(IReadOnlyCollection<UsageCounts> installations)
⋮----
var sum = installations.Aggregate(default(UsageCounts), (total, counts) => total + counts);
⋮----
public static class AdminUsageEndpoints
⋮----
public static async Task<IResult> DailyAsync(HttpContext http, GatewayDbContext database, CancellationToken cancellationToken)
⋮----
if (!UsageQuery.TryParse(http.Request.Query, UsageQuery.Daily, out var query, out var error))
⋮----
return Results.BadRequest(error);
⋮----
.Where(row => row.InstallationId == installation)
.ToDictionaryAsync(row => row.Day, UsageCounts.Of, cancellationToken);
⋮----
return Results.Ok(query.Days().Select(day => AdminUsageDay.Of(day, days.GetValueOrDefault(day))).ToList());
⋮----
.GroupBy(row => row.Day)
.Select(group => new
⋮----
Tokens = group.Sum(row => row.Tokens),
Requests = group.Sum(row => row.Requests),
RefusalsRateLimited = group.Sum(row => row.RefusalsRateLimited),
RefusalsBudgetExhausted = group.Sum(row => row.RefusalsBudgetExhausted),
UpstreamErrors = group.Sum(row => row.UpstreamErrors),
⋮----
.ToListAsync(cancellationToken))
.ToDictionary(
⋮----
day => new UsageCounts(day.Tokens, day.Requests, day.RefusalsRateLimited, day.RefusalsBudgetExhausted, day.UpstreamErrors));
⋮----
.Join(
⋮----
.GroupBy(joined => new { joined.Day, joined.Tier, joined.LicenceTier })
⋮----
Tokens = group.Sum(joined => joined.Row.Tokens),
Requests = group.Sum(joined => joined.Row.Requests),
RefusalsRateLimited = group.Sum(joined => joined.Row.RefusalsRateLimited),
RefusalsBudgetExhausted = group.Sum(joined => joined.Row.RefusalsBudgetExhausted),
UpstreamErrors = group.Sum(joined => joined.Row.UpstreamErrors),
⋮----
.ToListAsync(cancellationToken);
⋮----
var key = (group.Day, PolicyStore.RowFor(group.Tier, group.LicenceTier));
⋮----
split[key] = split.GetValueOrDefault(key) + new UsageCounts(
⋮----
return Results.Ok(query.Days()
.Select(day => AdminUsageDay.Of(
⋮----
fleet.GetValueOrDefault(day),
Enum.GetValues<PolicyTier>().ToDictionary(RowWords.Of, row => split.GetValueOrDefault((day, row)))))
.ToList());
⋮----
public static async Task<IResult> SummaryAsync(HttpContext http, GatewayDbContext database, CancellationToken cancellationToken)
⋮----
if (!UsageQuery.TryParse(http.Request.Query, UsageQuery.Summary, out var query, out var error))
⋮----
.GroupBy(row => row.InstallationId)
⋮----
.Select(installation => (
⋮----
Counts: new UsageCounts(
⋮----
.ToList();
⋮----
var ids = spent.Select(installation => installation.InstallationId).ToList();
⋮----
.AsNoTracking()
.Where(installation => ids.Contains(installation.Id))
.ToDictionaryAsync(
⋮----
installation => PolicyStore.RowFor(installation.Tier, installation.LicenceTier),
⋮----
PolicyTier? RowOf(Guid installation) => rows.TryGetValue(installation, out var row) ? row : null;
⋮----
.OrderByDescending(installation => installation.Counts.Tokens)
.ThenByDescending(installation => installation.Counts.Requests)
.ThenBy(installation => installation.InstallationId)
.Take(query.Limit)
.Select(installation => new AdminUsageInstallation(
⋮----
RowOf(installation.InstallationId) is { } row ? RowWords.Of(row) : null,
⋮----
return Results.Ok(new AdminUsageSummary(
⋮----
AdminUsageTotals.Of(spent.Select(installation => installation.Counts).ToList()),
Enum.GetValues<PolicyTier>().ToDictionary(
⋮----
served => AdminUsageTotals.Of(spent
.Where(installation => RowOf(installation.InstallationId) == served)
.Select(installation => installation.Counts)
.ToList())),
⋮----
private static IQueryable<DailyUsage> InRange(GatewayDbContext database, UsageQuery query) =>
database.DailyUsage.AsNoTracking().Where(row => row.Day >= query.From && row.Day <= query.To);
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/InstallationQuery.cs">
public static bool TryParse(
⋮----
if (query.Keys.FirstOrDefault(key => !Known.Contains(key, StringComparer.OrdinalIgnoreCase)) is { } unknown)
⋮----
error = AdminQueryError.Unknown(unknown, $"{unknown} is not a parameter of this list. It takes {string.Join(", ", Known)}.");
⋮----
if (query.Keys.FirstOrDefault(key => query[key].Count > 1) is { } repeated)
⋮----
error = AdminQueryError.Invalid(repeated, $"{repeated} is given more than once.");
⋮----
if (!Guid.TryParse(licence, out var id))
⋮----
error = AdminQueryError.Invalid("licence_id", "licence_id must be a GUID.");
⋮----
if (Value(query, "shared") is { } sharedValue && !bool.TryParse(sharedValue, out shared))
⋮----
error = AdminQueryError.Invalid("shared", "shared must be true or false.");
⋮----
if (!RowWords.TryParse(rowValue, out var named))
⋮----
error = AdminQueryError.Invalid(
⋮----
$"row must be one of {string.Join(", ", Enum.GetValues<PolicyTier>().Select(RowWords.Of))}.");
⋮----
revoked = status.ToLowerInvariant() switch
⋮----
error = AdminQueryError.Invalid("status", "status must be active or revoked.");
⋮----
if (!DateTimeOffset.TryParse(
⋮----
error = AdminQueryError.Invalid("seen_since", "seen_since must be an instant, such as 2026-09-26T00:00:00Z.");
⋮----
if (!AppVersions.IsVersion(version))
⋮----
error = AdminQueryError.Invalid("app_version_below", "app_version_below must be a version, such as 1.7.0.");
⋮----
InstallationSort? named = sortValue.ToLowerInvariant() switch
⋮----
error = AdminQueryError.Invalid("sort", "sort must be created, last_seen or tokens_used.");
⋮----
if (!int.TryParse(limitValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out limit))
⋮----
error = AdminQueryError.Invalid("limit", $"limit must be a whole number. Above {MaximumLimit}, it is {MaximumLimit}.");
⋮----
if (!int.TryParse(offsetValue, NumberStyles.None, CultureInfo.InvariantCulture, out offset))
⋮----
error = AdminQueryError.Invalid("offset", "offset must be a whole number, 0 or more.");
⋮----
parsed = new InstallationQuery(
⋮----
licenceId is null ? Math.Clamp(limit, 1, MaximumLimit) : null,
⋮----
private static string? Value(IQueryCollection query, string name) =>
query.TryGetValue(name, out var values) ? values.ToString() : null;
⋮----
public static AdminQueryError Unknown(string parameter, string message) => new("unknown_parameter", parameter, message);
⋮----
public static AdminQueryError Invalid(string parameter, string message) => new("invalid_parameter", parameter, message);
</file>

<file path="src/KnowledgeFabric.AiGateway/Admin/UsageQuery.cs">
public IEnumerable<DateOnly> Days()
⋮----
for (var day = From; day <= To; day = day.AddDays(1))
⋮----
public static bool TryParse(
⋮----
if (query.Keys.FirstOrDefault(key => !known.Contains(key, StringComparer.OrdinalIgnoreCase)) is { } unknown)
⋮----
error = AdminQueryError.Unknown(unknown, $"{unknown} is not a parameter of this report. It takes {string.Join(", ", known)}.");
⋮----
if (query.Keys.FirstOrDefault(key => query[key].Count > 1) is { } repeated)
⋮----
error = AdminQueryError.Invalid(repeated, $"{repeated} is given more than once.");
⋮----
error = AdminQueryError.Invalid("to", "to must be on or after from.");
⋮----
error = AdminQueryError.Invalid("to", $"The range is at most {MaximumDays} days, from and to included. Ask for a longer one in parts.");
⋮----
if (!Guid.TryParse(installation, out var id))
⋮----
error = AdminQueryError.Invalid("installation_id", "installation_id must be a GUID.");
⋮----
&& !int.TryParse(limitValue, NumberStyles.Integer, CultureInfo.InvariantCulture, out limit))
⋮----
error = AdminQueryError.Invalid("limit", $"limit must be a whole number. Above {MaximumLimit}, it is {MaximumLimit}.");
⋮----
parsed = new UsageQuery(from, to, installationId, Math.Clamp(limit, 1, MaximumLimit));
⋮----
private static bool TryDate(
⋮----
error = AdminQueryError.Invalid(name, $"{name} is required: {meaning}, such as 2026-09-01.");
⋮----
if (!DateOnly.TryParseExact(value, DateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out date))
⋮----
error = AdminQueryError.Invalid(name, $"{name} must be a date, such as 2026-09-01, with no time: the ledger counts in UTC days.");
⋮----
private static string? Value(IQueryCollection query, string name) =>
query.TryGetValue(name, out var values) ? values.ToString() : null;
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/DailyUsage.cs">
public sealed class DailyUsage
⋮----
public static UsageCounts Of(DailyUsage row) => new(
⋮----
public static class DailyUsageLedger
⋮----
public static async Task AddAsync(
⋮----
var row = new DailyUsage
⋮----
database.DailyUsage.Add(row);
⋮----
await database.SaveChangesAsync(cancellationToken);
⋮----
database.Entry(row).State = EntityState.Detached;
⋮----
private static Task<int> UpdateAsync(
⋮----
.Where(row => row.InstallationId == installation && row.Day == day)
.ExecuteUpdateAsync(
⋮----
.SetProperty(row => row.Tokens, row => row.Tokens + counts.Tokens)
.SetProperty(row => row.Requests, row => row.Requests + counts.Requests)
.SetProperty(row => row.RefusalsRateLimited, row => row.RefusalsRateLimited + counts.RefusalsRateLimited)
.SetProperty(row => row.RefusalsBudgetExhausted, row => row.RefusalsBudgetExhausted + counts.RefusalsBudgetExhausted)
.SetProperty(row => row.UpstreamErrors, row => row.UpstreamErrors + counts.UpstreamErrors),
⋮----
public static DateOnly DayOf(DateTimeOffset instant) => DateOnly.FromDateTime(instant.UtcDateTime);
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/DatabaseMigrator.cs">
internal sealed class DatabaseMigrator(
⋮----
ILogger<DatabaseMigrator> logger) : IHostedLifecycleService
⋮----
public async Task StartingAsync(CancellationToken cancellationToken)
⋮----
logger.LogInformation("Database migration on startup is off; the schema is assumed to be current.");
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
await database.OpenConnectionAsync(cancellationToken);
⋮----
await database.ExecuteSqlRawAsync(
⋮----
await database.MigrateAsync(cancellationToken);
⋮----
await database.CloseConnectionAsync();
⋮----
logger.LogInformation("Database schema is current.");
⋮----
public Task StartAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StartedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StoppingAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StopAsync(CancellationToken cancellationToken) => Task.CompletedTask;
⋮----
public Task StoppedAsync(CancellationToken cancellationToken) => Task.CompletedTask;
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/DatabaseOptions.cs">
public sealed class DatabaseOptions
⋮----
internal bool NamesAHostAndDatabase()
⋮----
var builder = new NpgsqlConnectionStringBuilder(ConnectionString);
return !string.IsNullOrWhiteSpace(builder.Host) && !string.IsNullOrWhiteSpace(builder.Database);
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/DataServiceCollectionExtensions.cs">
public static class DataServiceCollectionExtensions
⋮----
public static IServiceCollection AddGatewayDatabase(this IServiceCollection services, IConfiguration configuration)
⋮----
.Bind(configuration.GetSection(DatabaseOptions.SectionName))
.ValidateDataAnnotations()
.Validate(
options => options.NamesAHostAndDatabase(),
⋮----
.ValidateOnStart();
⋮----
builder.UseNpgsql(options.ConnectionString, npgsql => npgsql.EnableRetryOnFailure());
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/DesignTimeGatewayDbContextFactory.cs">
internal sealed class DesignTimeGatewayDbContextFactory : IDesignTimeDbContextFactory<GatewayDbContext>
⋮----
public GatewayDbContext CreateDbContext(string[] args) =>
⋮----
.UseNpgsql("Host=design-time;Database=kf_ai_gateway")
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/EnrolmentAttempt.cs">
public sealed class EnrolmentAttempt
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/GatewayDbContext.cs">
public sealed class GatewayDbContext(DbContextOptions<GatewayDbContext> options) : DbContext(options)
⋮----
private static ValueConverter<TEnum, string> ContractWords<TEnum>()
where TEnum : struct, Enum =>
new(value => value.ToString().ToLowerInvariant(), word => Enum.Parse<TEnum>(word, true));
⋮----
private static ValueConverter<BudgetPeriod, string> BudgetPeriodConverter() =>
new(period => BudgetPeriodWords.Of(period), word => BudgetPeriodWords.Parse(word));
⋮----
protected override void OnModelCreating(ModelBuilder modelBuilder)
⋮----
installation.HasKey(i => i.Id);
⋮----
installation.HasIndex(i => i.CredentialHash).IsUnique();
⋮----
installation.Property(i => i.CredentialHash).HasMaxLength(32).IsRequired();
⋮----
installation.Property(i => i.AppVersion).HasMaxLength(32).IsRequired();
installation.Property(i => i.Tier).HasConversion(ContractWords<Tier>()).HasMaxLength(16).IsRequired();
installation.Property(i => i.LicenceStatus).HasConversion(ContractWords<LicenceStatus>()).HasMaxLength(16).IsRequired();
installation.Property(i => i.LicenceReason).HasMaxLength(16);
⋮----
installation.Property(i => i.LicenceBudgetPeriod).HasConversion(BudgetPeriodConverter()).HasMaxLength(32);
⋮----
installation.Property(i => i.LicenceTier).HasConversion(ContractWords<LicenceTier>()).HasMaxLength(16);
⋮----
installation.HasIndex(i => i.LicenceId);
⋮----
tierPolicy.HasKey(p => p.Tier);
tierPolicy.Property(p => p.Tier).HasConversion(ContractWords<PolicyTier>()).HasMaxLength(16);
tierPolicy.Property(p => p.BudgetPeriod).HasConversion(BudgetPeriodConverter()).HasMaxLength(32).IsRequired();
⋮----
tierPolicy.HasData(
new TierPolicy
⋮----
RequestWindow = TimeSpan.FromMinutes(1),
⋮----
gatewayPolicy.ToTable(table =>
table.HasCheckConstraint("CK_GatewayPolicy_Singleton", $"\"Id\" = {Data.GatewayPolicy.SingletonId}"));
gatewayPolicy.Property(p => p.Id).ValueGeneratedNever();
gatewayPolicy.Property(p => p.MinimumAppVersion).HasMaxLength(32).IsRequired();
⋮----
gatewayPolicy.HasData(new GatewayPolicy
⋮----
globalSpend.ToTable(table =>
table.HasCheckConstraint("CK_GlobalSpend_Singleton", $"\"Id\" = {Data.GlobalSpend.SingletonId}"));
globalSpend.Property(s => s.Id).ValueGeneratedNever();
⋮----
globalSpend.HasData(new GlobalSpend
⋮----
usage.HasKey(u => new { u.InstallationId, u.Day });
⋮----
usage.HasIndex(u => u.Day);
⋮----
attempt.HasIndex(a => new { a.SourceAddress, a.AttemptedAt });
⋮----
attempt.Property(a => a.SourceAddress).HasMaxLength(64).IsRequired();
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/GlobalSpend.cs">
public sealed class GlobalSpend
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/Installation.cs">
public sealed class Installation
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/Policy.cs">
public static class BudgetPeriodWords
⋮----
public static string Of(BudgetPeriod period) => period == BudgetPeriod.CalendarMonth ? CalendarMonth : Rolling30Days;
⋮----
public static bool TryParse(string? word, out BudgetPeriod period)
⋮----
public static BudgetPeriod Parse(string word) =>
TryParse(word, out var period) ? period : throw new InvalidOperationException($"'{word}' is not a budget period.");
⋮----
public sealed class TierPolicy
⋮----
public sealed class GatewayPolicy
</file>

<file path="src/KnowledgeFabric.AiGateway/Data/PolicyStore.cs">
public sealed class PolicyStore(GatewayDbContext database)
⋮----
public async Task<TierPolicy> ForAsync(Installation installation, CancellationToken cancellationToken) =>
⋮----
public static TierPolicy Serve(Installation installation, TierPolicy row) =>
LicenceLimitsFor(installation).Over(row);
⋮----
public static LicenceLimits LicenceLimitsFor(Installation installation) =>
installation.Tier == Tier.Licensed ? LicenceLimits.Of(installation) : LicenceLimits.None;
⋮----
public static PolicyTier RowFor(Installation installation) =>
⋮----
public static PolicyTier RowFor(Tier tier, LicenceTier? licenceTier) =>
⋮----
public static Expression<Func<Installation, bool>> OnRow(PolicyTier row) => row switch
⋮----
_ => throw new ArgumentOutOfRangeException(nameof(row), row, "There is no such policy row."),
⋮----
public async Task<TierPolicy> RowAsync(PolicyTier tier, CancellationToken cancellationToken) =>
await database.TierPolicies.AsNoTracking().SingleOrDefaultAsync(p => p.Tier == tier, cancellationToken)
?? throw new InvalidOperationException($"There is no policy row for the {tier} tier; the migration seeds one.");
⋮----
public async Task<GatewayPolicy> GatewayAsync(CancellationToken cancellationToken) =>
await database.GatewayPolicy.AsNoTracking().SingleOrDefaultAsync(cancellationToken)
?? throw new InvalidOperationException("There is no gateway policy row; the migration seeds one.");
</file>

<file path="src/KnowledgeFabric.AiGateway/Enrolment/AppVersions.cs">
public static class AppVersions
⋮----
public static bool IsAtLeast(string? version, string? minimum)
⋮----
public static bool IsVersion(string? value) => TryParse(value, out _);
⋮----
private static bool TryParse(string? value, out Version version)
⋮----
version = new Version();
⋮----
if (string.IsNullOrWhiteSpace(value))
⋮----
var core = value.Trim().Split('-', '+')[0];
⋮----
return Version.TryParse(core, out var parsed) && (version = parsed) is not null;
</file>

<file path="src/KnowledgeFabric.AiGateway/Enrolment/ClientAddress.cs">
public static class ClientAddress
⋮----
public static string Of(HttpContext http)
⋮----
var forwarded = http.Request.Headers[ForwardedForHeader].ToString();
⋮----
if (!string.IsNullOrWhiteSpace(forwarded))
⋮----
var appended = forwarded.Split(',')[^1];
⋮----
private static string? Parse(string entry)
⋮----
var trimmed = entry.Trim();
⋮----
if (IPAddress.TryParse(trimmed, out var address))
⋮----
return address.ToString();
⋮----
return IPEndPoint.TryParse(trimmed, out var endpoint) ? endpoint.Address.ToString() : null;
</file>

<file path="src/KnowledgeFabric.AiGateway/Enrolment/Credential.cs">
public static class Credential
⋮----
public static string Issue() => Prefix + Base64Url(RandomNumberGenerator.GetBytes(32));
⋮----
public static byte[] Fingerprint(string credential) =>
SHA256.HashData(Encoding.UTF8.GetBytes(credential));
⋮----
private static string Base64Url(byte[] bytes) =>
Convert.ToBase64String(bytes).TrimEnd('=').Replace('+', '-').Replace('/', '_');
</file>

<file path="src/KnowledgeFabric.AiGateway/Enrolment/EnrolmentEndpoints.cs">
public static class EnrolmentEndpoints
⋮----
public static void MapEnrolment(this WebApplication app)
⋮----
app.MapPost("/v1/installations", EnrolAsync);
⋮----
app.MapGet("/v1/installation", SelfAsync).RequireAuthorization(InstallationAuthentication.Policy);
app.MapPut("/v1/installation/licence", LicenceAsync).RequireAuthorization(InstallationAuthentication.Policy);
⋮----
private static async Task<IResult> EnrolAsync(
⋮----
return GatewayErrors.Refuse(http, GatewayErrors.InvalidRequest);
⋮----
|| !Guid.TryParse(payload.InstallationId, out var installationId)
|| string.IsNullOrWhiteSpace(payload.AppVersion))
⋮----
http.Tag(SpanTags.Installation, installationId.ToString());
⋮----
var gatewayPolicy = await policies.GatewayAsync(cancellationToken);
var address = ClientAddress.Of(http);
⋮----
if (await velocity.RetryAfterAsync(gatewayPolicy, address, cancellationToken) is { } retryAfter)
⋮----
return GatewayErrors.Refuse(http, GatewayErrors.EnrolmentRateLimited, retryAfter: retryAfter);
⋮----
if (!AppVersions.IsAtLeast(payload.AppVersion, gatewayPolicy.MinimumAppVersion))
⋮----
return GatewayErrors.Refuse(http, GatewayErrors.AppVersionUnsupported);
⋮----
var now = clock.GetUtcNow();
var credential = Credential.Issue();
⋮----
.FirstOrDefaultAsync(row => row.Id == installationId, cancellationToken);
⋮----
installation = NewInstallation(installationId, payload, licences.Evaluate(payload.Licence), credential, now);
database.Installations.Add(installation);
⋮----
velocity.Record(gatewayPolicy, address);
await database.SaveChangesAsync(cancellationToken);
⋮----
http.Tag(SpanTags.Enrolment, enrolment);
⋮----
await velocity.PruneAsync(gatewayPolicy, cancellationToken);
⋮----
var tier = await policies.ForAsync(installation, cancellationToken);
var requests = windows.Peek(installation.Id, tier, now);
⋮----
http.Tag(SpanTags.Row, RowWords.Of(tier.Tier));
⋮----
QuotaHeaders.Write(http.Response, QuotaSnapshot.Of(installation, tier, requests, now));
⋮----
return Results.Json(
new EnrolmentResponse(credential, TierWords.Of(installation.Tier), LicenceState.Of(installation)),
⋮----
private static async Task<IResult> SelfAsync(
⋮----
var installation = http.CurrentInstallation()!;
var policy = await policies.ForAsync(installation, cancellationToken);
⋮----
var quota = QuotaSnapshot.Of(installation, policy, windows.Peek(installation.Id, policy, now), now);
⋮----
return Results.Ok(new InstallationResponse(
⋮----
TierWords.Of(installation.Tier),
⋮----
QuotaState.Of(quota),
LicenceState.Of(installation)));
⋮----
private static async Task<IResult> LicenceAsync(
⋮----
var licence = licences.Evaluate(payload.Licence);
⋮----
return GatewayErrors.Refuse(http, GatewayErrors.LicenceRejected, reason: licence.Reason);
⋮----
database.Installations.Attach(installation);
licence.ApplyTo(installation);
⋮----
http.SetTierPolicy(await policies.ForAsync(installation, cancellationToken));
⋮----
return Results.Ok(new LicenceUpdateResponse(TierWords.Of(installation.Tier), LicenceState.Of(installation)));
⋮----
private static Installation NewInstallation(
⋮----
CredentialHash = Credential.Fingerprint(credential),
⋮----
private static void ReEnrol(
⋮----
installation.CredentialHash = Credential.Fingerprint(credential);
⋮----
if (string.IsNullOrWhiteSpace(payload.Licence))
⋮----
installation.Lapse(now);
⋮----
licences.Evaluate(payload.Licence).ApplyTo(installation);
</file>

<file path="src/KnowledgeFabric.AiGateway/Enrolment/EnrolmentVelocity.cs">
public sealed class EnrolmentVelocity(GatewayDbContext database, TimeProvider clock)
⋮----
private static readonly TimeSpan Hour = TimeSpan.FromHours(1);
private static readonly TimeSpan Day = TimeSpan.FromDays(1);
⋮----
public async Task<TimeSpan?> RetryAfterAsync(GatewayPolicy policy, string address, CancellationToken cancellationToken)
⋮----
var now = clock.GetUtcNow();
⋮----
.AsNoTracking()
.Where(attempt => attempt.SourceAddress == address && attempt.AttemptedAt > now - Day)
.Select(attempt => attempt.AttemptedAt)
.ToListAsync(cancellationToken);
⋮----
public void Record(GatewayPolicy policy, string address)
⋮----
database.EnrolmentAttempts.Add(new EnrolmentAttempt
⋮----
AttemptedAt = clock.GetUtcNow(),
⋮----
public Task PruneAsync(GatewayPolicy policy, CancellationToken cancellationToken)
⋮----
var cutoff = clock.GetUtcNow() - Day;
⋮----
return database.EnrolmentAttempts.Where(attempt => attempt.AttemptedAt <= cutoff).ExecuteDeleteAsync(cancellationToken);
⋮----
private static TimeSpan? Drains(
⋮----
var inWindow = enrolments.Where(at => at > now - window).OrderBy(at => at).ToList();
⋮----
return drains > TimeSpan.Zero ? drains : TimeSpan.FromSeconds(1);
</file>

<file path="src/KnowledgeFabric.AiGateway/Enrolment/InstallationAuthentication.cs">
public static class InstallationAuthentication
⋮----
public static Installation? CurrentInstallation(this HttpContext http) =>
http.Items.TryGetValue(ItemsKey, out var found) ? found as Installation : null;
⋮----
internal static void SetCurrentInstallation(this HttpContext http, Installation installation) =>
⋮----
public sealed class NotInstallationAuthenticated
⋮----
public static readonly NotInstallationAuthenticated Instance = new();
⋮----
public sealed class InstallationAuthenticationHandler(
⋮----
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
⋮----
private static readonly TimeSpan LastSeenResolution = TimeSpan.FromMinutes(5);
⋮----
protected override async Task<AuthenticateResult> HandleAuthenticateAsync()
⋮----
if (Context.GetEndpoint()?.Metadata.GetMetadata<NotInstallationAuthenticated>() is not null
⋮----
return AuthenticateResult.NoResult();
⋮----
var fingerprint = Credential.Fingerprint(credential);
⋮----
.AsNoTracking()
.FirstOrDefaultAsync(row => row.CredentialHash == fingerprint, Context.RequestAborted);
⋮----
Context.SetCurrentInstallation(installation);
⋮----
Context.Tag(SpanTags.Installation, installation.Id.ToString());
⋮----
var identity = new ClaimsIdentity(
⋮----
new Claim(ClaimTypes.NameIdentifier, installation.Id.ToString()),
new Claim(InstallationAuthentication.ActiveClaim, installation.RevokedAt is null ? "true" : "false"),
⋮----
return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name));
⋮----
protected override Task HandleChallengeAsync(AuthenticationProperties properties) =>
GatewayErrors.RefuseAsync(Context, GatewayErrors.InstallationUnknown);
⋮----
protected override Task HandleForbiddenAsync(AuthenticationProperties properties) =>
GatewayErrors.RefuseAsync(Context, GatewayErrors.InstallationRevoked);
⋮----
private string? Bearer()
⋮----
var header = Request.Headers.Authorization.ToString();
⋮----
return header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
? header["Bearer ".Length..].Trim()
⋮----
private async Task LapseExpiredLicenceAsync(Installation installation)
⋮----
if (!installation.Lapse(clock.GetUtcNow()))
⋮----
.Where(row => row.Id == installation.Id && row.Tier == Tier.Licensed)
.ExecuteUpdateAsync(rows => rows
.SetProperty(row => row.Tier, installation.Tier)
.SetProperty(row => row.LicenceStatus, installation.LicenceStatus)
.SetProperty(row => row.LicenceReason, installation.LicenceReason)
.SetProperty(row => row.LicenceTier, installation.LicenceTier)
.SetProperty(row => row.LicenceId, installation.LicenceId)
.SetProperty(row => row.LicenceTokenBudget, installation.LicenceTokenBudget)
.SetProperty(row => row.LicenceBudgetPeriod, installation.LicenceBudgetPeriod)
.SetProperty(row => row.LicenceRequestsPerMinute, installation.LicenceRequestsPerMinute),
⋮----
private async Task StampLastSeenAsync(Installation installation)
⋮----
var now = clock.GetUtcNow();
⋮----
.Where(row => row.Id == installation.Id)
.ExecuteUpdateAsync(rows => rows.SetProperty(row => row.LastSeenAt, now), Context.RequestAborted);
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/ChatForwarder.cs">
public sealed class ChatForwarder(
⋮----
public async Task<ChatOutcome> ForwardAsync(HttpContext http, JsonObject request, int maxPredictTokens, bool streaming)
⋮----
using var total = CancellationTokenSource.CreateLinkedTokenSource(http.RequestAborted);
total.CancelAfter(settings.TotalTimeout);
⋮----
using var firstByte = CancellationTokenSource.CreateLinkedTokenSource(total.Token);
firstByte.CancelAfter(settings.FirstByteTimeout);
⋮----
using var upstreamRequest = adapter.Request(request, settings.Model, maxPredictTokens);
⋮----
HttpResponseMessage upstream;
⋮----
upstream = await client.SendAsync(upstreamRequest, HttpCompletionOption.ResponseHeadersRead, firstByte.Token);
⋮----
logger.LogWarning("The provider could not be reached ({Failure}).", exception.HttpRequestError);
⋮----
logger.LogWarning("The provider refused the request with {UpstreamStatus}.", (int)upstream.StatusCode);
⋮----
await using var body = await upstream.Content.ReadAsStreamAsync(firstByte.Token);
⋮----
private async Task<ChatOutcome> RelayAsync(
⋮----
await foreach (var chunk in adapter.ChunksAsync(body, firstByte.Token))
⋮----
firstByte.CancelAfter(Timeout.InfiniteTimeSpan);
⋮----
tokens += ChatScrub.IsDone(chunk) ? ChatScrub.Tokens(chunk) : 0;
⋮----
await WriteAsync(http, ChatScrub.Chunk(chunk), streaming, total.Token);
⋮----
return new ChatOutcome(tokens, UpstreamFailed: false);
⋮----
logger.LogWarning(
"The answer failed mid-stream after {Tokens} tokens ({Failure}).", tokens, exception.GetType().Name);
⋮----
http.Abort();
⋮----
return new ChatOutcome(tokens, UpstreamFailed: true);
⋮----
logger.LogWarning("The provider answered with an empty body.");
⋮----
private static void Begin(HttpContext http, bool streaming)
⋮----
private static async Task WriteAsync(HttpContext http, JsonObject chunk, bool streaming, CancellationToken cancellationToken)
⋮----
var json = chunk.ToJsonString();
⋮----
await http.Response.WriteAsync(streaming ? json + "\n" : json, Encoding.UTF8, cancellationToken);
⋮----
await http.Response.Body.FlushAsync(cancellationToken);
⋮----
private async Task<ChatOutcome> TimedOutAsync(HttpContext http, string stage)
⋮----
logger.LogWarning("The provider timed out while {Stage}.", stage);
⋮----
private static async Task<ChatOutcome> RefuseAsync(HttpContext http, GatewayError error)
⋮----
await GatewayErrors.RefuseAsync(http, error);
⋮----
return new ChatOutcome(Tokens: 0, UpstreamFailed: true);
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/ChatScrub.cs">
internal static class ChatScrub
⋮----
public static JsonObject Chunk(JsonObject upstream)
⋮----
var scrubbed = new JsonObject
⋮----
: value.DeepClone();
⋮----
private static JsonObject Message(JsonObject upstream)
⋮----
var scrubbed = new JsonObject();
⋮----
scrubbed[field] = value.DeepClone();
⋮----
public static long Tokens(JsonObject chunk) =>
⋮----
public static bool IsDone(JsonObject chunk) =>
⋮----
private static long Count(JsonNode? node) =>
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/ForwardingEndpoints.cs">
public static class ForwardingEndpoints
⋮----
public static void MapForwarding(this WebApplication app)
⋮----
var forwarded = app.MapGroup("/api")
.RequireAuthorization(InstallationAuthentication.Policy)
⋮----
.RequireRateLimiting(QuotaPolicies.Requests)
⋮----
forwarded.MapGet("/tags", Tags);
⋮----
forwarded.MapPost("/show", (Delegate)Show);
forwarded.MapPost("/chat", Chat);
⋮----
private static IResult Tags() =>
Results.Json(new JsonObject
⋮----
["models"] = new JsonArray(new JsonObject
⋮----
["details"] = ModelAlias.Details(),
⋮----
private static async Task<IResult> Show(HttpContext http)
⋮----
return GatewayErrors.Refuse(http, GatewayErrors.InvalidRequest);
⋮----
if (!ModelAlias.Matches(Text(request["model"]) ?? Text(request["name"])))
⋮----
return GatewayErrors.Refuse(http, GatewayErrors.ModelUnknown);
⋮----
return Results.Json(new JsonObject
⋮----
["capabilities"] = new JsonArray(ModelAlias.Capabilities.Select(c => (JsonNode?)c).ToArray()),
⋮----
private static async Task<IResult> Chat(
⋮----
if (!ModelAlias.Matches(Text(request["model"])))
⋮----
var installation = http.CurrentInstallation()!;
var policy = await policies.ForAsync(installation, http.RequestAborted);
⋮----
var outcome = await forwarder.ForwardAsync(
⋮----
http.Tag(SpanTags.ChatTokens, outcome.Tokens);
http.Tag(SpanTags.ChatUpstream, outcome.UpstreamFailed ? SpanTags.Upstream.Failed : SpanTags.Upstream.Ok);
⋮----
tally.Count(installation.Id, Counted.UpstreamError);
⋮----
await ledger.RecordAsync(installation, policy, outcome.Tokens);
⋮----
private static async Task<JsonObject?> ReadAsync(HttpContext http)
⋮----
return await JsonNode.ParseAsync(http.Request.Body, cancellationToken: http.RequestAborted) as JsonObject;
⋮----
private static string? Text(JsonNode? node) =>
⋮----
private static bool Flag(JsonNode? node, bool fallback) =>
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/ForwardingOptions.cs">
public sealed class ForwardingOptions
⋮----
public static readonly TimeSpan PlatformIdleTimeout = TimeSpan.FromSeconds(230);
⋮----
public TimeSpan ConnectTimeout { get; set; } = TimeSpan.FromSeconds(5);
⋮----
public TimeSpan FirstByteTimeout { get; set; } = TimeSpan.FromSeconds(45);
⋮----
public TimeSpan TotalTimeout { get; set; } = TimeSpan.FromSeconds(180);
⋮----
internal sealed class ForwardingOptionsValidator : IValidateOptions<ForwardingOptions>
⋮----
public ValidateOptionsResult Validate(string? name, ForwardingOptions options)
⋮----
failures.Add($"{label} must be greater than zero.");
⋮----
failures.Add(
⋮----
failures.Add("Forwarding:ConnectTimeout must not exceed Forwarding:FirstByteTimeout.");
⋮----
failures.Add("Forwarding:FirstByteTimeout must not exceed Forwarding:TotalTimeout.");
⋮----
return failures.Count == 0 ? ValidateOptionsResult.Success : ValidateOptionsResult.Fail(failures);
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/ForwardingServiceCollectionExtensions.cs">
public static class ForwardingServiceCollectionExtensions
⋮----
public static IServiceCollection AddChatForwarding(this IServiceCollection services, IConfiguration configuration)
⋮----
.Bind(configuration.GetSection(ForwardingOptions.SectionName))
⋮----
.Configure(options => options.ApiKey = configuration[ForwardingOptions.ApiKeySetting])
.ValidateDataAnnotations()
.ValidateOnStart();
⋮----
if (!string.IsNullOrWhiteSpace(options.ApiKey))
⋮----
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", options.ApiKey);
⋮----
.ConfigurePrimaryHttpMessageHandler(provider => new SocketsHttpHandler
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/IChatAdapter.cs">
public interface IChatAdapter
⋮----
HttpRequestMessage Request(JsonObject request, string model, int maxPredictTokens);
⋮----
IAsyncEnumerable<JsonObject> ChunksAsync(Stream body, CancellationToken cancellationToken);
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/ModelAlias.cs">
public static class ModelAlias
⋮----
public static bool Matches(string? model) =>
string.Equals(model, Name, StringComparison.Ordinal)
|| string.Equals(model, $"{Name}:latest", StringComparison.Ordinal);
⋮----
public static JsonObject Details() =>
⋮----
["families"] = new JsonArray(Name),
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/OllamaChatAdapter.cs">
public sealed class OllamaChatAdapter : IChatAdapter
⋮----
public HttpRequestMessage Request(JsonObject request, string model, int maxPredictTokens)
⋮----
var upstream = request.DeepClone().AsObject();
⋮----
return new HttpRequestMessage(HttpMethod.Post, ChatPath)
⋮----
Content = new StringContent(upstream.ToJsonString(), Encoding.UTF8, "application/json"),
⋮----
private static void Clamp(JsonObject upstream, int maxPredictTokens)
⋮----
options["num_predict"] = requested < 0 ? maxPredictTokens : Math.Min(requested, maxPredictTokens);
⋮----
public async IAsyncEnumerable<JsonObject> ChunksAsync(
⋮----
var count = await body.ReadAsync(read, cancellationToken);
⋮----
throw new InvalidDataException(
⋮----
Array.Resize(ref pending, Math.Max(length + count, pending.Length * 2));
⋮----
Array.Copy(read, 0, pending, length, count);
⋮----
while (Array.IndexOf(pending, (byte)'\n', scanned, length - scanned) is var end and >= 0)
⋮----
Array.Copy(pending, end + 1, pending, 0, length - end - 1);
⋮----
private static JsonObject? Parse(byte[] buffer, int length)
⋮----
var line = buffer.AsSpan(0, length).TrimEnd((byte)'\r');
⋮----
var reader = new Utf8JsonReader(line);
⋮----
return JsonNode.Parse(ref reader) as JsonObject;
⋮----
throw new InvalidDataException("The provider sent a line that is not JSON.");
</file>

<file path="src/KnowledgeFabric.AiGateway/Forwarding/TokenLedger.cs">
public sealed class TokenLedger(GatewayDbContext database, TimeProvider clock)
⋮----
public async Task RecordAsync(Installation installation, TierPolicy policy, long tokens)
⋮----
var now = clock.GetUtcNow();
var period = BudgetWindow.For(installation, policy, now).Start;
var month = BudgetWindow.StartOfUtcMonth(now);
⋮----
.Where(row => row.Id == installation.Id)
.ExecuteUpdateAsync(
⋮----
.SetProperty(row => row.TokensUsed, row => row.BudgetPeriodStart < period ? tokens : row.TokensUsed + tokens)
.SetProperty(row => row.BudgetPeriodStart, row => row.BudgetPeriodStart < period ? period : row.BudgetPeriodStart),
⋮----
.Where(row => row.Id == GlobalSpend.SingletonId)
⋮----
.SetProperty(row => row.TokensUsed, row => row.PeriodStart < month ? tokens : row.TokensUsed + tokens)
.SetProperty(row => row.PeriodStart, row => row.PeriodStart < month ? month : row.PeriodStart),
⋮----
await DailyUsageLedger.AddAsync(
⋮----
DailyUsageLedger.DayOf(now),
new UsageCounts { Tokens = tokens },
</file>

<file path="src/KnowledgeFabric.AiGateway/Licensing/LicenceEvaluation.cs">
public static readonly LicenceOutcome Absent = new(LicenceStatus.Absent, null, null);
⋮----
public void ApplyTo(Installation installation)
⋮----
Limits.ApplyTo(installation);
⋮----
public interface ILicenceEvaluator
⋮----
LicenceOutcome Evaluate(string? licence);
</file>

<file path="src/KnowledgeFabric.AiGateway/Licensing/LicenceExpiry.cs">
public static class LicenceExpiry
⋮----
public static bool Lapse(this Installation installation, DateTimeOffset now)
⋮----
LicenceLimits.None.ApplyTo(installation);
</file>

<file path="src/KnowledgeFabric.AiGateway/Licensing/LicenceLimits.cs">
public static readonly LicenceLimits None = new(null, null, null);
⋮----
public static class Attributes
⋮----
public static class Periods
⋮----
public static string Of(BudgetPeriod period) =>
⋮----
public static LicenceLimits Of(Installation installation) =>
⋮----
public void ApplyTo(Installation installation)
⋮----
public TierPolicy Over(TierPolicy tier) => this == None
⋮----
: new TierPolicy
⋮----
RequestWindow = RequestsPerMinute is null ? tier.RequestWindow : TimeSpan.FromMinutes(1),
</file>

<file path="src/KnowledgeFabric.AiGateway/Licensing/StandardLicenceEvaluator.cs">
public sealed class StandardLicenceEvaluator(
⋮----
ILogger<StandardLicenceEvaluator> logger) : ILicenceEvaluator
⋮----
public static class Causes
⋮----
public static class Tiers
⋮----
public LicenceOutcome Evaluate(string? licence)
⋮----
if (string.IsNullOrWhiteSpace(licence))
⋮----
var outcome = Read(licence.TrimStart('﻿'), clock.GetUtcNow());
⋮----
logger.LogInformation("Licence reported as {Reason}; the contract's reason is {Cause}", outcome.Reason, cause);
⋮----
private LicenceOutcome Read(string xml, DateTimeOffset now)
⋮----
License licence;
⋮----
licence = License.Load(xml);
⋮----
if (attributes.ContainsKey("TrialDays"))
⋮----
return new LicenceOutcome(LicenceStatus.Rejected, LicenceWords.Expired, expiresAt) { Cause = LicenceWords.Expired };
⋮----
return new LicenceOutcome(LicenceStatus.Accepted, null, expiresAt)
⋮----
private Guid? ReadId(License licence)
⋮----
Guid id;
⋮----
logger.LogInformation("The licence's Id cannot be read, so no licence id is recorded");
⋮----
private LicenceTier ReadTier(IDictionary<string, string> attributes)
⋮----
if (!attributes.TryGetValue(Tiers.Attribute, out var raw) || string.IsNullOrWhiteSpace(raw) || raw == Tiers.Standard)
⋮----
logger.LogInformation("The licence's {Attribute} is not one this gateway knows; the standard allowance applies", Tiers.Attribute);
⋮----
private LicenceLimits ReadLimits(IDictionary<string, string> attributes)
⋮----
return new LicenceLimits(tokens, ReadPeriod(attributes), requests is { } rpm ? (int)Math.Min(rpm, int.MaxValue) : null);
⋮----
private long? ReadLimit(IDictionary<string, string> attributes, string name)
⋮----
if (!attributes.TryGetValue(name, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
if (long.TryParse(raw.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value > 0)
⋮----
logger.LogInformation("The licence's {Attribute} cannot be read, so it allows nothing", name);
⋮----
private BudgetPeriod? ReadPeriod(IDictionary<string, string> attributes)
⋮----
if (!attributes.TryGetValue(LicenceLimits.Attributes.Period, out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
switch (raw.Trim())
⋮----
logger.LogInformation("The licence's {Attribute} is not a period this gateway knows; the tier's applies", LicenceLimits.Attributes.Period);
⋮----
private bool IsGenuine(License licence)
⋮----
if (licence.VerifySignature(key))
⋮----
private static DateTimeOffset? ExpiresAt(DateTime expiration)
⋮----
if (expiration >= DateTime.MaxValue.AddDays(-2))
⋮----
DateTimeKind.Local => expiration.ToUniversalTime(),
_ => DateTime.SpecifyKind(expiration, DateTimeKind.Utc),
⋮----
return new DateTimeOffset(utc, TimeSpan.Zero);
⋮----
private static bool SchemaSupported(IDictionary<string, string> attributes)
⋮----
if (!attributes.TryGetValue("schemaVersion", out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
return int.TryParse(raw, NumberStyles.Integer, CultureInfo.InvariantCulture, out var version)
⋮----
private static bool InForce(IDictionary<string, string> attributes, DateTimeOffset now)
⋮----
if (!attributes.TryGetValue("validFrom", out var raw) || string.IsNullOrWhiteSpace(raw))
⋮----
return DateTimeOffset.TryParse(
⋮----
private static LicenceOutcome Refused(string reason, string? cause = null) =>
</file>

<file path="src/KnowledgeFabric.AiGateway/Licensing/TrustedLicenceKeys.cs">
public static class TrustedLicenceKeys
</file>

<file path="src/KnowledgeFabric.AiGateway/Properties/launchSettings.json">
{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "iisSettings": {
    "windowsAuthentication": false,
    "anonymousAuthentication": true,
    "iisExpress": {
      "applicationUrl": "http://localhost:32949",
      "sslPort": 44349
    }
  },
  "profiles": {
    "http": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "http://localhost:5170",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "https": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": true,
      "applicationUrl": "https://localhost:7253;http://localhost:5170",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    },
    "IIS Express": {
      "commandName": "IISExpress",
      "launchBrowser": true,
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/AdmissionFilter.cs">
internal sealed class AdmissionFilter(GlobalBrake brake, UsageTally tally, TimeProvider clock, ILogger<AdmissionFilter> logger)
: IEndpointFilter
⋮----
private static readonly TimeSpan PausedBackoff = TimeSpan.FromMinutes(1);
⋮----
public async ValueTask<object?> InvokeAsync(EndpointFilterInvocationContext context, EndpointFilterDelegate next)
⋮----
var installation = http.CurrentInstallation()!;
var policy = http.TierPolicy()!;
⋮----
var now = clock.GetUtcNow();
var budget = BudgetWindow.For(installation, policy, now);
⋮----
tally.Count(installation.Id, Counted.Request | Counted.BudgetExhausted);
⋮----
return GatewayErrors.Refuse(
⋮----
tally.Count(installation.Id, Counted.Request);
⋮----
if ((await brake.ReadAsync(now, http.RequestAborted)).Tripped)
⋮----
logger.LogWarning("The global spend brake is tripped; the request was refused.");
⋮----
return GatewayErrors.Refuse(http, GatewayErrors.ServicePaused, retryAfter: PausedBackoff);
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/BudgetWindow.cs">
private static readonly TimeSpan Rolling = TimeSpan.FromDays(30);
⋮----
public static BudgetWindow For(Installation installation, TierPolicy policy, DateTimeOffset now)
⋮----
var end = monthly ? start.AddMonths(1) : start + Rolling;
⋮----
return new BudgetWindow(start, end, installation.BudgetPeriodStart >= start ? installation.TokensUsed : 0);
⋮----
private static DateTimeOffset StartOfRollingPeriod(DateTimeOffset enrolled, DateTimeOffset now)
⋮----
var lapsed = Math.Max(0, (now - enrolled).Ticks) / Rolling.Ticks;
⋮----
return enrolled + TimeSpan.FromTicks(lapsed * Rolling.Ticks);
⋮----
public static BudgetWindow For(GlobalSpend spend, DateTimeOffset now)
⋮----
return new BudgetWindow(month, month.AddMonths(1), spend.PeriodStart >= month ? spend.TokensUsed : 0);
⋮----
public static DateTimeOffset StartOfUtcMonth(DateTimeOffset instant)
⋮----
var utc = instant.ToUniversalTime();
⋮----
return new DateTimeOffset(utc.Year, utc.Month, 1, 0, 0, 0, TimeSpan.Zero);
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/GlobalBrake.cs">
public sealed class GlobalBrake(GatewayDbContext database, PolicyStore policies)
⋮----
public async Task<BrakeState> ReadAsync(DateTimeOffset now, CancellationToken cancellationToken)
⋮----
var policy = await policies.GatewayAsync(cancellationToken);
⋮----
var spend = await database.GlobalSpend.AsNoTracking().SingleOrDefaultAsync(cancellationToken)
?? throw new InvalidOperationException("There is no global spend row; the migration seeds one.");
⋮----
return new BrakeState(policy.GlobalTokenCeiling, BudgetWindow.For(spend, now));
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/InstallationRateLimiter.cs">
internal sealed class InstallationRateLimiter(WindowKey key, RequestWindow window, RequestWindows owner) : RateLimiter
⋮----
public override RateLimiterStatistics GetStatistics() => new()
⋮----
CurrentAvailablePermits = window.Peek(key.PermitLimit).Remaining,
⋮----
TotalSuccessfulLeases = Interlocked.Read(ref _granted),
TotalFailedLeases = Interlocked.Read(ref _rejected),
⋮----
protected override RateLimitLease AttemptAcquireCore(int permitCount)
⋮----
if (window.TryAcquire(key.PermitLimit, permitCount, out var retryAfter))
⋮----
Interlocked.Increment(ref _granted);
⋮----
return new WindowLease(acquired: true, retryAfter: null);
⋮----
Interlocked.Increment(ref _rejected);
⋮----
return new WindowLease(acquired: false, retryAfter);
⋮----
protected override ValueTask<RateLimitLease> AcquireAsyncCore(int permitCount, CancellationToken cancellationToken) =>
⋮----
protected override void Dispose(bool disposing) => Release();
⋮----
protected override ValueTask DisposeAsyncCore()
⋮----
private void Release()
⋮----
if (Interlocked.Exchange(ref _released, 1) == 0)
⋮----
owner.Release(key, window);
⋮----
private sealed class WindowLease(bool acquired, TimeSpan? retryAfter) : RateLimitLease
⋮----
public override bool TryGetMetadata(string metadataName, out object? metadata)
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/QuotaContext.cs">
public static class QuotaContext
⋮----
public static TierPolicy? TierPolicy(this HttpContext http) =>
http.Items.TryGetValue(ItemsKey, out var found) ? found as TierPolicy : null;
⋮----
internal static void SetTierPolicy(this HttpContext http, TierPolicy policy)
⋮----
http.Tag(SpanTags.Row, RowWords.Of(policy.Tier));
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/QuotaHeaderMiddleware.cs">
public sealed class QuotaHeaderMiddleware(RequestDelegate next)
⋮----
public async Task InvokeAsync(
⋮----
if (http.CurrentInstallation() is { } installation)
⋮----
var policy = await policies.ForAsync(installation, http.RequestAborted);
http.SetTierPolicy(policy);
⋮----
http.Response.OnStarting(() =>
⋮----
var current = http.TierPolicy() ?? policy;
var now = clock.GetUtcNow();
var requests = windows.Peek(installation.Id, current, now);
⋮----
QuotaHeaders.Write(http.Response, QuotaSnapshot.Of(installation, current, requests, now));
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/QuotaHeaders.cs">
public static class QuotaHeaders
⋮----
public static void Write(HttpResponse response, QuotaSnapshot quota)
⋮----
headers["X-KF-Tier"] = TierWords.Of(quota.Tier);
⋮----
private static string Number(long value) => value.ToString(CultureInfo.InvariantCulture);
⋮----
private static string Instant(DateTimeOffset value) =>
value.ToUniversalTime().ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", CultureInfo.InvariantCulture);
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/QuotaServiceCollectionExtensions.cs">
public static class QuotaPolicies
⋮----
public static class QuotaServiceCollectionExtensions
⋮----
public static IServiceCollection AddGatewayQuota(this IServiceCollection services)
⋮----
services.AddRateLimiter(options =>
⋮----
if (http.CurrentInstallation() is { } installation)
⋮----
.Count(installation.Id, Counted.Request | Counted.RateLimited);
⋮----
return new ValueTask(GatewayErrors.RefuseAsync(
⋮----
rejected.Lease.TryGetMetadata(MetadataName.RetryAfter, out var retryAfter) ? retryAfter : null));
⋮----
options.AddPolicy(QuotaPolicies.Requests, http =>
⋮----
if (http.CurrentInstallation() is not { } installation || http.TierPolicy() is not { } policy)
⋮----
return RateLimitPartition.GetNoLimiter(default(WindowKey));
⋮----
var key = WindowKey.For(installation.Id, policy);
⋮----
return RateLimitPartition.Get(key, windows.For);
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/QuotaSnapshot.cs">
public static QuotaSnapshot Of(
⋮----
var budget = BudgetWindow.For(installation, policy, now);
⋮----
return new QuotaSnapshot(
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/RequestAllowance.cs">
public static RequestAllowance Untouched(TierPolicy policy, DateTimeOffset now) =>
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/RequestWindow.cs">
internal sealed class RequestWindow
⋮----
private readonly TimeProvider _clock;
private readonly TimeSpan _segment;
private readonly TimeSpan _window;
⋮----
private DateTimeOffset _headStart;
private DateTimeOffset _emptySince;
⋮----
_segment = TimeSpan.FromTicks(Math.Max(1, window.Ticks / Segments));
⋮----
_headStart = clock.GetUtcNow();
⋮----
public RequestAllowance Peek(int limit)
⋮----
public bool TryAcquire(int limit, int permits, out TimeSpan retryAfter)
⋮----
private DateTimeOffset Advance()
⋮----
var now = _clock.GetUtcNow();
⋮----
Array.Clear(_spent);
⋮----
_headStart += TimeSpan.FromTicks(steps * _segment.Ticks);
⋮----
private RequestAllowance Allowance(int limit, DateTimeOffset now) =>
new(limit, Math.Max(0, limit - _used), ResetAt(limit, now));
⋮----
private DateTimeOffset ResetAt(int limit, DateTimeOffset now)
</file>

<file path="src/KnowledgeFabric.AiGateway/Quota/RequestWindows.cs">
public static WindowKey For(Guid installation, TierPolicy policy) =>
⋮----
public sealed class RequestWindows(TimeProvider clock)
⋮----
public RequestAllowance Peek(Guid installation, TierPolicy policy, DateTimeOffset now) =>
_windows.TryGetValue((installation, policy.RequestWindow.Ticks), out var window)
? window.Peek(policy.RequestsPerWindow)
: RequestAllowance.Untouched(policy, now);
⋮----
internal InstallationRateLimiter For(WindowKey key)
⋮----
var window = _windows.GetOrAdd(key.Window, _ => new RequestWindow(TimeSpan.FromTicks(key.WindowTicks), clock));
⋮----
return new InstallationRateLimiter(key, window, this);
⋮----
internal void Release(WindowKey key, RequestWindow window)
⋮----
_windows.TryRemove(new KeyValuePair<(Guid, long), RequestWindow>(key.Window, window));
</file>

<file path="src/KnowledgeFabric.AiGateway/Telemetry/HealthCheckNoiseProcessor.cs">
internal sealed class HealthCheckNoiseProcessor : BaseProcessor<Activity>
⋮----
public override void OnEnd(Activity activity)
⋮----
private static bool IsHealthCheck(Activity activity) =>
⋮----
private static bool Failed(Activity activity) =>
⋮----
|| activity.GetTagItem("http.response.status_code") is not 200;
⋮----
private static string? Tag(Activity activity, string name) => activity.GetTagItem(name) as string;
</file>

<file path="src/KnowledgeFabric.AiGateway/Telemetry/SpanTags.cs">
public static class SpanTags
⋮----
public static class Upstream
⋮----
public static class Enrolments
⋮----
public static void Tag(this HttpContext http, string name, object? value) =>
http.Features.Get<IHttpActivityFeature>()?.Activity.SetTag(name, value);
</file>

<file path="src/KnowledgeFabric.AiGateway/Telemetry/SpendReport.cs">
public sealed class SpendReport(
⋮----
ILogger<SpendReport> logger) : BackgroundService
⋮----
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(15);
⋮----
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
⋮----
using var timer = new PeriodicTimer(Interval, clock);
⋮----
while (await timer.WaitForNextTickAsync(stoppingToken))
⋮----
public async Task<SpendReading?> ReportAsync(CancellationToken cancellationToken)
⋮----
SpendReading reading;
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
reading = await ReadAsync(database, clock.GetUtcNow(), cancellationToken);
⋮----
logger.LogWarning(exception, "The spend report could not read the daily usage; no reading was written this interval.");
⋮----
logger.LogInformation(
⋮----
reading.Day.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture),
⋮----
public static async Task<SpendReading> ReadAsync(GatewayDbContext database, DateTimeOffset now, CancellationToken cancellationToken)
⋮----
var today = DailyUsageLedger.DayOf(now);
var first = today.AddDays(-TrailingDays);
⋮----
.AsNoTracking()
.Where(row => row.Day >= first && row.Day <= today)
.GroupBy(row => row.Day)
.Select(group => new { Day = group.Key, Tokens = group.Sum(row => row.Tokens) })
.ToListAsync(cancellationToken);
⋮----
var tokensToday = days.Where(day => day.Day == today).Sum(day => day.Tokens);
var trailing = days.Where(day => day.Day < today).Sum(day => day.Tokens);
⋮----
return new SpendReading(today, tokensToday, trailing / TrailingDays);
</file>

<file path="src/KnowledgeFabric.AiGateway/Telemetry/TelemetryServiceCollectionExtensions.cs">
public static class TelemetryServiceCollectionExtensions
⋮----
public static bool HasSink(IConfiguration configuration) =>
!string.IsNullOrWhiteSpace(configuration[ConnectionStringSetting]);
⋮----
public static IServiceCollection AddGatewayTelemetry(this IServiceCollection services, IConfiguration configuration)
⋮----
var telemetry = services.AddOpenTelemetry();
⋮----
telemetry.UseAzureMonitor(options =>
⋮----
telemetry.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation())
.WithMetrics(metrics => metrics
⋮----
.AddHttpClientInstrumentation());
⋮----
services.ConfigureOpenTelemetryTracerProvider(
tracing => tracing.AddProcessor(new HealthCheckNoiseProcessor()));
⋮----
services.AddHostedService(provider => provider.GetRequiredService<SpendReport>());
</file>

<file path="src/KnowledgeFabric.AiGateway/Usage/UsageFlush.cs">
public sealed class UsageFlush(
⋮----
ILogger<UsageFlush> logger) : BackgroundService
⋮----
public static readonly TimeSpan Interval = TimeSpan.FromMinutes(1);
⋮----
private readonly SemaphoreSlim _flushing = new(1, 1);
⋮----
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
⋮----
using var timer = new PeriodicTimer(Interval, clock);
⋮----
while (await timer.WaitForNextTickAsync(stoppingToken))
⋮----
public override async Task StopAsync(CancellationToken cancellationToken)
⋮----
await base.StopAsync(cancellationToken);
⋮----
logger.LogWarning("Shutdown ran out of time before the daily usage was written; the last interval's counts are lost.");
⋮----
public async Task FlushAsync(CancellationToken cancellationToken)
⋮----
await _flushing.WaitAsync(cancellationToken);
⋮----
var pending = tally.Drain();
⋮----
await using var scope = scopes.CreateAsyncScope();
⋮----
await DailyUsageLedger.AddAsync(database, installation, day, counts, cancellationToken);
⋮----
tally.Restore(pending.Skip(written));
⋮----
logger.LogWarning(
⋮----
_flushing.Release();
</file>

<file path="src/KnowledgeFabric.AiGateway/Usage/UsageServiceCollectionExtensions.cs">
public static class UsageServiceCollectionExtensions
⋮----
public static IServiceCollection AddDailyUsage(this IServiceCollection services)
⋮----
services.AddHostedService(provider => provider.GetRequiredService<UsageFlush>());
</file>

<file path="src/KnowledgeFabric.AiGateway/Usage/UsageTally.cs">
public sealed class UsageTally(TimeProvider clock)
⋮----
public void Count(Guid installation, Counted what)
⋮----
var counts = new UsageCounts(
⋮----
Requests: what.HasFlag(Counted.Request) ? 1 : 0,
RefusalsRateLimited: what.HasFlag(Counted.RateLimited) ? 1 : 0,
RefusalsBudgetExhausted: what.HasFlag(Counted.BudgetExhausted) ? 1 : 0,
UpstreamErrors: what.HasFlag(Counted.UpstreamError) ? 1 : 0);
⋮----
var key = (installation, DailyUsageLedger.DayOf(clock.GetUtcNow()));
⋮----
public IReadOnlyList<KeyValuePair<(Guid Installation, DateOnly Day), UsageCounts>> Drain()
⋮----
public void Restore(IEnumerable<KeyValuePair<(Guid Installation, DateOnly Day), UsageCounts>> unwritten)
⋮----
private void Add((Guid Installation, DateOnly Day) key, UsageCounts counts) =>
_pending[key] = _pending.GetValueOrDefault(key) + counts;
</file>

<file path="src/KnowledgeFabric.AiGateway/appsettings.Development.json">
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Information",
      "Microsoft.EntityFrameworkCore": "Information",
      "KnowledgeFabric.AiGateway.Forwarding": "Debug"
    }
  },
  "Database": {
    "ConnectionString": "Host=localhost;Port=5432;Database=kf_ai_gateway;Username=kf_ai_gateway;Password=kf_ai_gateway"
  },
  "Forwarding": {
    "UpstreamAddress": "http://localhost:11434/",
    "Model": "llama3.1"
  }
}
</file>

<file path="src/KnowledgeFabric.AiGateway/appsettings.json">
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
</file>

<file path="src/KnowledgeFabric.AiGateway/Contracts.cs">
public static QuotaState Of(QuotaSnapshot quota) => new(
new RequestQuota(quota.RequestsLimit, quota.RequestsRemaining, quota.RequestsResetAt),
new TokenQuota(quota.TokensLimit, quota.TokensUsed, quota.TokensResetAt));
⋮----
public static readonly LicenceState Absent = new(LicenceWords.Absent, null, null);
⋮----
public static LicenceState Of(Installation installation) => new(
installation.LicenceStatus.ToString().ToLowerInvariant(),
⋮----
public sealed class ContractInstantConverter : JsonConverter<DateTimeOffset>
⋮----
public override DateTimeOffset Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options) =>
DateTimeOffset.Parse(
reader.GetString()!,
⋮----
public override void Write(Utf8JsonWriter writer, DateTimeOffset value, JsonSerializerOptions options) =>
writer.WriteStringValue(value.ToUniversalTime().ToString(Format, CultureInfo.InvariantCulture));
⋮----
public static class TierWords
⋮----
public static string Of(Tier tier) => tier.ToString().ToLowerInvariant();
⋮----
public static class LicenceWords
</file>

<file path="src/KnowledgeFabric.AiGateway/GatewayErrors.cs">
public static class GatewayErrors
⋮----
public static readonly GatewayError InvalidRequest = new(
⋮----
public static readonly GatewayError InstallationUnknown = new(
⋮----
public static readonly GatewayError InstallationRevoked = new(
⋮----
public static readonly GatewayError ModelUnknown = new(
⋮----
public static readonly GatewayError LicenceRejected = new(
⋮----
public static readonly GatewayError AppVersionUnsupported = new(
⋮----
public static readonly GatewayError EnrolmentRateLimited = new(
⋮----
public static readonly GatewayError RateLimited = new(
⋮----
public static readonly GatewayError TokenBudgetExhausted = new(
⋮----
public static readonly GatewayError UpstreamUnavailable = new(
⋮----
public static readonly GatewayError ServicePaused = new(
⋮----
public static readonly GatewayError UpstreamTimeout = new(
⋮----
public static IResult Refuse(
⋮----
http.Tag(SpanTags.ErrorCode, error.Code);
⋮----
var seconds = (int)Math.Ceiling((retryAfter ?? TimeSpan.FromMinutes(1)).TotalSeconds);
http.Response.Headers.RetryAfter = Math.Max(1, seconds).ToString(System.Globalization.CultureInfo.InvariantCulture);
⋮----
return Results.Json(
new ErrorBody(error.Code, error.Message) { Reason = reason, ResetsAt = resetsAt },
⋮----
public static Task RefuseAsync(
⋮----
Refuse(http, error, retryAfter: retryAfter).ExecuteAsync(http);
</file>

<file path="src/KnowledgeFabric.AiGateway/Program.cs">
var builder = WebApplication.CreateBuilder(args);
⋮----
builder.Services.AddGatewayDatabase(builder.Configuration);
⋮----
builder.Services.AddGatewayTelemetry(builder.Configuration);
⋮----
builder.Services.AddSingleton(TimeProvider.System);
⋮----
builder.Services.AddGatewayQuota();
⋮----
builder.Services.AddDailyUsage();
⋮----
builder.Services.AddSingleton<ILicenceEvaluator>(services => new StandardLicenceEvaluator(
⋮----
builder.Services.AddAdmin(builder.Configuration);
⋮----
builder.Services.ConfigureHttpJsonOptions(options =>
⋮----
options.SerializerOptions.Converters.Add(new ContractInstantConverter());
⋮----
builder.Services.AddAuthentication(InstallationAuthentication.Scheme)
⋮----
builder.Services.AddAuthorizationBuilder()
.AddPolicy(InstallationAuthentication.Policy, policy => policy
.AddAuthenticationSchemes(InstallationAuthentication.Scheme)
.RequireAuthenticatedUser()
.RequireClaim(InstallationAuthentication.ActiveClaim, "true"));
⋮----
builder.Services.AddChatForwarding(builder.Configuration);
⋮----
builder.Services.AddHealthChecks();
⋮----
var app = builder.Build();
⋮----
app.MapHealthChecks("/health");
⋮----
app.UseAuthentication();
app.UseAuthorization();
⋮----
app.UseRateLimiter();
⋮----
app.MapEnrolment();
⋮----
app.MapAdmin();
⋮----
app.MapForwarding();
⋮----
app.Run();
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/Properties/launchSettings.json">
{
  "$schema": "http://json.schemastore.org/launchsettings.json",
  "profiles": {
    "stub": {
      "commandName": "Project",
      "dotnetRunMessages": true,
      "launchBrowser": false,
      "applicationUrl": "http://localhost:5080",
      "environmentVariables": {
        "ASPNETCORE_ENVIRONMENT": "Development"
      }
    }
  }
}
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/appsettings.json">
{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*"
}
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/Contracts.cs">
public static readonly LicenceState Absent = new(LicenceStatus.Absent, null, null);
⋮----
internal static class Tiers
⋮----
internal static class LicenceTiers
⋮----
internal static class LicenceStatus
⋮----
internal static class LicenceReason
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/ControlEndpoints.cs">
internal static class ControlEndpoints
⋮----
public static void MapControl(this WebApplication app)
⋮----
var control = app.MapGroup("/stub");
⋮----
control.MapPost("/force", Force);
control.MapDelete("/force", ClearForce);
control.MapPost("/policy", Policy);
control.MapGet("/state", State);
control.MapPost("/reset", Reset);
⋮----
private static async Task<IResult> Force(HttpContext http, StubState state)
⋮----
if (request?.Code is null || !StubErrors.TryGet(request.Code, out _))
⋮----
return Results.BadRequest(new
⋮----
Codes = StubErrors.Catalogue.Select(e => e.Code).Order().ToArray(),
⋮----
return Results.BadRequest(new { Error = "times must be at least 1, or absent to force until cleared." });
⋮----
state.Force(request.Code, request.Times);
return Results.NoContent();
⋮----
private static IResult ClearForce(StubState state)
⋮----
state.ClearForce();
⋮----
private static async Task<IResult> Policy(HttpContext http, StubState state)
⋮----
return Results.BadRequest(new { Error = "A policy body is required." });
⋮----
return Results.BadRequest(new { Error = "An allowance must be at least 1." });
⋮----
state.SetPolicy(request.Tier, request.RequestsPerMinute, request.TokenBudget);
⋮----
private static IResult State(StubState state) => Results.Ok(state.Report());
⋮----
private static IResult Reset(StubState state)
⋮----
state.Reset();
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/OllamaEndpoints.cs">
internal static class OllamaEndpoints
⋮----
public static void MapOllama(this WebApplication app)
⋮----
var forwarded = app.MapGroup("/api")
⋮----
forwarded.MapGet("/tags", Tags);
⋮----
forwarded.MapPost("/show", (Delegate)Show);
forwarded.MapPost("/chat", Chat);
⋮----
private static IResult Tags() =>
Results.Json(new JsonObject
⋮----
["models"] = new JsonArray(new JsonObject
⋮----
private static async Task<IResult> Show(HttpContext http)
⋮----
return StubErrors.Refuse(http, StubErrors.InvalidRequest);
⋮----
return StubErrors.Refuse(http, StubErrors.ModelUnknown);
⋮----
return Results.Json(new JsonObject
⋮----
["capabilities"] = new JsonArray("completion", "tools"),
⋮----
private static async Task<IResult> Chat(HttpContext http, StubState state, TimeProvider clock)
⋮----
var replyTokens = Tokens(message.ToJsonString().Length);
⋮----
var createdAt = clock.GetUtcNow().UtcDateTime.ToString("o");
⋮----
await WriteLine(http, new JsonObject
⋮----
await WriteLine(http, Final(createdAt, promptTokens, replyTokens, new JsonObject
⋮----
await http.Response.WriteAsync(Final(createdAt, promptTokens, replyTokens, message).ToJsonString());
⋮----
state.CountTokens(http.Installation(), promptTokens + replyTokens);
⋮----
private static JsonObject Final(string createdAt, long promptTokens, long replyTokens, JsonObject message) =>
⋮----
private static JsonObject Answer(JsonObject request, JsonArray? messages)
⋮----
var tool = request["tools"] is JsonArray tools ? Text(tools.FirstOrDefault()?["function"]?["name"]) : null;
⋮----
return new JsonObject { ["role"] = "assistant", ["content"] = Reply };
⋮----
return new JsonObject
⋮----
["tool_calls"] = new JsonArray(new JsonObject
⋮----
["function"] = new JsonObject
⋮----
["arguments"] = new JsonObject(),
⋮----
private static JsonObject Details() =>
⋮----
["families"] = new JsonArray(Alias),
⋮----
private static long Tokens(int characters) => (characters + 3) / 4;
⋮----
private static bool IsAlias(string? model) =>
⋮----
&& (string.Equals(model, Alias, StringComparison.Ordinal)
|| string.Equals(model, $"{Alias}:latest", StringComparison.Ordinal));
⋮----
private static async Task<JsonObject?> Read(HttpContext http)
⋮----
return await JsonNode.ParseAsync(http.Request.Body) as JsonObject;
⋮----
private static async Task WriteLine(HttpContext http, JsonNode chunk)
⋮----
await http.Response.WriteAsync(chunk.ToJsonString() + "\n");
await http.Response.Body.FlushAsync();
⋮----
private static string? Text(JsonNode? node) =>
⋮----
private static bool Flag(JsonNode? node, bool fallback) =>
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/Program.cs">
var builder = WebApplication.CreateBuilder(args);
⋮----
builder.Services.AddSingleton(TimeProvider.System);
builder.Services.AddStubLicenceClock(builder.Configuration);
⋮----
builder.Services.AddHealthChecks();
⋮----
builder.Services.ConfigureHttpJsonOptions(options =>
⋮----
var app = builder.Build();
⋮----
app.Use(async (context, next) =>
⋮----
app.MapHealthChecks("/health");
app.MapV1();
app.MapOllama();
app.MapControl();
⋮----
app.Logger.LogWarning(
⋮----
app.Run();
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/StubCredential.cs">
internal static class StubCredential
⋮----
public static string Issue() =>
Prefix + Convert.ToBase64String(RandomNumberGenerator.GetBytes(32))
.TrimEnd('=')
.Replace('+', '-')
.Replace('/', '_');
⋮----
public static string Fingerprint(string credential) =>
Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(credential)));
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/StubErrors.cs">
internal static class StubErrors
⋮----
public static ErrorDefinition Get(string code) => Definitions[code];
⋮----
public static bool TryGet(string code, [MaybeNullWhen(false)] out ErrorDefinition definition) =>
Definitions.TryGetValue(code, out definition);
⋮----
public static IResult Refuse(
⋮----
http.Response.Headers.RetryAfter = Math.Max(1, retryAfterSeconds).ToString();
⋮----
var body = new ErrorBody(definition.Code, definition.Message)
⋮----
return Results.Json(body, statusCode: definition.Status);
⋮----
public static IResult Refuse(HttpContext http, string code) => Refuse(http, Get(code));
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/StubFilters.cs">
internal static class HttpContextExtensions
⋮----
public static void SetInstallation(this HttpContext http, StubInstallation installation) =>
⋮----
public static StubInstallation Installation(this HttpContext http) =>
⋮----
internal static class StubForce
⋮----
public static ErrorDefinition? For(HttpContext http, StubState state, ErrorSurface surface)
⋮----
if (http.Request.Headers.TryGetValue(Header, out var values)
⋮----
&& StubErrors.TryGet(code, out var requested)
⋮----
return state.TakeForced(surface);
⋮----
internal sealed class InstallationFilter(StubState state) : IEndpointFilter
⋮----
public async ValueTask<object?> InvokeAsync(
⋮----
var forced = StubForce.For(http, state, ErrorSurface.Authenticated);
⋮----
return StubErrors.Refuse(http, forced);
⋮----
if (Credential(http) is not { } credential || state.Find(credential) is not { } installation)
⋮----
return StubErrors.Refuse(http, StubErrors.InstallationUnknown);
⋮----
http.SetInstallation(installation);
⋮----
http.Response.OnStarting(() =>
⋮----
WriteQuotaHeaders(http, state.Snapshot(installation), installation.Tier);
⋮----
return StubErrors.Refuse(
⋮----
? state.Snapshot(installation).Tokens.ResetAt
⋮----
private static string? Credential(HttpContext http)
⋮----
var header = http.Request.Headers.Authorization.ToString();
⋮----
return header.StartsWith("Bearer ", StringComparison.OrdinalIgnoreCase)
? header["Bearer ".Length..].Trim()
⋮----
public static void WriteQuotaHeaders(HttpContext http, QuotaState quota, string tier)
⋮----
headers["X-KF-Requests-Limit"] = quota.Requests.Limit.ToString();
headers["X-KF-Requests-Remaining"] = quota.Requests.Remaining.ToString();
⋮----
headers["X-KF-Tokens-Limit"] = quota.Tokens.Limit.ToString();
headers["X-KF-Tokens-Used"] = quota.Tokens.Used.ToString();
⋮----
private static string Instant(DateTime value) =>
value.ToString("yyyy-MM-dd'T'HH:mm:ss'Z'", System.Globalization.CultureInfo.InvariantCulture);
⋮----
internal sealed class AdmissionFilter(StubState state) : IEndpointFilter
⋮----
var admission = state.Admit(http.Installation());
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/StubLicences.cs">
public static readonly LicenceLimits None = new(null, null, null);
⋮----
public static readonly StubLicence Absent = new(LicenceState.Absent, LicenceLimits.None);
⋮----
public static readonly StubLicence Unverifiable =
new(new LicenceState(LicenceStatus.Rejected, LicenceReason.Unverifiable, null), LicenceLimits.None);
⋮----
internal static class StubLicences
⋮----
private static readonly TimeSpan DefaultTerm = TimeSpan.FromDays(365);
⋮----
public static StubLicence Evaluate(string? licenceXml, LicenceClock clock)
⋮----
if (string.IsNullOrWhiteSpace(licenceXml))
⋮----
XElement root;
⋮----
root = XElement.Parse(licenceXml);
⋮----
if (!string.Equals(root.Name.LocalName, "License", StringComparison.OrdinalIgnoreCase))
⋮----
var now = clock.GetUtcNow();
⋮----
var expiresAt = new DateTime(
⋮----
return new StubLicence(new LicenceState(LicenceStatus.Rejected, LicenceReason.Expired, expiresAt), LicenceLimits.None);
⋮----
return new StubLicence(new LicenceState(LicenceStatus.Accepted, null, expiresAt), Limits(attributes), Tier(attributes));
⋮----
private static string Tier(Dictionary<string, string> attributes) =>
attributes.TryGetValue("tier", out var tier) && tier == LicenceTiers.Enterprise
⋮----
private static LicenceLimits Limits(Dictionary<string, string> attributes)
⋮----
return new LicenceLimits(
⋮----
requests is { } rpm ? (int)Math.Min(rpm, int.MaxValue) : null);
⋮----
private static Dictionary<string, string> Attributes(XElement root) =>
root.Elements()
.Where(e => string.Equals(e.Name.LocalName, "LicenseAttributes", StringComparison.OrdinalIgnoreCase))
.Elements()
.Where(e => string.Equals(e.Name.LocalName, "Attribute", StringComparison.OrdinalIgnoreCase))
.Select(e => (Name: (string?)e.Attribute("name"), e.Value))
.Where(a => a.Name is not null)
.GroupBy(a => a.Name!, StringComparer.Ordinal)
.ToDictionary(g => g.Key, g => g.First().Value, StringComparer.Ordinal);
⋮----
private static long? Limit(Dictionary<string, string> attributes, string name) =>
⋮----
: long.TryParse(raw.Trim(), NumberStyles.None, CultureInfo.InvariantCulture, out var value) && value > 0 ? value : 0;
⋮----
private static string? Value(Dictionary<string, string> attributes, string name) =>
attributes.TryGetValue(name, out var raw) && !string.IsNullOrWhiteSpace(raw) ? raw : null;
⋮----
private static DateTimeOffset? Expiry(XElement root)
⋮----
var element = root.Elements()
.FirstOrDefault(e => string.Equals(e.Name.LocalName, "Expiration", StringComparison.OrdinalIgnoreCase));
⋮----
&& DateTimeOffset.TryParse(
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/StubOptions.cs">
public sealed class StubOptions
⋮----
internal static DateTimeOffset? ParseInstant(string value) =>
DateTimeOffset.TryParse(
⋮----
internal sealed class LicenceClock(TimeProvider clock, IOptions<StubOptions> options)
⋮----
public DateTimeOffset GetUtcNow() => options.Value.LicenceInstant ?? clock.GetUtcNow();
⋮----
public static class StubServiceCollectionExtensions
⋮----
public static IServiceCollection AddStubLicenceClock(this IServiceCollection services, IConfiguration configuration)
⋮----
.Bind(configuration.GetSection(StubOptions.SectionName))
.Validate(
options => options.LicenceClock is null || StubOptions.ParseInstant(options.LicenceClock) is not null,
⋮----
.ValidateOnStart();
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/StubState.cs">
public static readonly TierPolicy Evaluation = new(30, 1_000_000);
⋮----
public static readonly TierPolicy Standard = new(120, 10_000_000);
⋮----
public static readonly TierPolicy Enterprise = new(120, 10_000_000);
⋮----
internal sealed class StubInstallation
⋮----
public static readonly Admission Admitted = new(null, 0, null);
⋮----
internal sealed class StubState(TimeProvider clock)
⋮----
private static readonly TimeSpan RequestWindow = TimeSpan.FromMinutes(1);
⋮----
private static readonly TimeSpan RollingBudgetPeriod = TimeSpan.FromDays(30);
⋮----
private TierPolicy _evaluation = TierPolicy.Evaluation;
private TierPolicy _standard = TierPolicy.Standard;
private TierPolicy _enterprise = TierPolicy.Enterprise;
⋮----
public (string Credential, StubInstallation Installation) Enrol(
⋮----
var now = clock.GetUtcNow();
⋮----
var credential = StubCredential.Issue();
var fingerprint = StubCredential.Fingerprint(credential);
⋮----
if (_installations.TryGetValue(id, out var existing))
⋮----
_byFingerprint.Remove(existing.Fingerprint);
⋮----
var created = new StubInstallation
⋮----
public StubInstallation? Find(string credential)
⋮----
if (!_byFingerprint.TryGetValue(fingerprint, out var id))
⋮----
installation.LastSeen = clock.GetUtcNow();
⋮----
public Admission Admit(StubInstallation installation)
⋮----
return new Admission(
StubErrors.Get(StubErrors.RateLimited),
⋮----
StubErrors.Get(StubErrors.TokenBudgetExhausted),
⋮----
public void CountTokens(StubInstallation installation, long tokens)
⋮----
public QuotaState Snapshot(StubInstallation installation)
⋮----
return new QuotaState(
new RequestQuota(
⋮----
Math.Max(0, policy.RequestsPerMinute - installation.RequestsUsed),
⋮----
new TokenQuota(
⋮----
public ErrorDefinition? TakeForced(ErrorSurface surface)
⋮----
var definition = StubErrors.Get(_forced.Code);
⋮----
public void SetLicence(StubInstallation installation, StubLicence licence)
⋮----
public void Force(string code, int? times)
⋮----
_forced = new ForcedError(code, times);
⋮----
public void ClearForce()
⋮----
public void SetPolicy(string? tier, int? requestsPerMinute, long? tokenBudget)
⋮----
public void Reset()
⋮----
_installations.Clear();
_byFingerprint.Clear();
⋮----
public StubStateReport Report()
⋮----
.Select(i => new StubInstallationReport(
⋮----
.OrderBy(i => i.InstallationId)
.ToList();
⋮----
return new StubStateReport(
⋮----
private TierPolicy PolicyFor(StubInstallation installation)
⋮----
return new TierPolicy(
⋮----
private void Roll(StubInstallation installation, DateTimeOffset now)
⋮----
private static BudgetPeriod PeriodOf(StubInstallation installation) =>
⋮----
private static DateTimeOffset BudgetStartAt(StubInstallation installation, DateTimeOffset now) =>
⋮----
? new DateTimeOffset(now.UtcDateTime.Year, now.UtcDateTime.Month, 1, 0, 0, 0, TimeSpan.Zero)
: installation.EnrolledAt + TimeSpan.FromTicks(
Math.Max(0, (now - installation.EnrolledAt).Ticks) / RollingBudgetPeriod.Ticks * RollingBudgetPeriod.Ticks);
⋮----
private static DateTimeOffset BudgetResetAt(StubInstallation installation, DateTimeOffset now) =>
⋮----
? BudgetStartAt(installation, now).AddMonths(1)
⋮----
private static int SecondsUntil(DateTimeOffset instant, DateTimeOffset now) =>
(int)Math.Max(1, Math.Ceiling((instant - now).TotalSeconds));
⋮----
private static DateTime Truncate(DateTimeOffset instant)
⋮----
return new DateTime(utc.Ticks - (utc.Ticks % TimeSpan.TicksPerSecond), DateTimeKind.Utc);
</file>

<file path="src/KnowledgeFabric.AiGateway.Stub/V1Endpoints.cs">
internal static class V1Endpoints
⋮----
public static void MapV1(this WebApplication app)
⋮----
app.MapPost("/v1/installations", Enrol);
app.MapGet("/v1/installation", Self).AddEndpointFilter<InstallationFilter>();
app.MapPut("/v1/installation/licence", Licence).AddEndpointFilter<InstallationFilter>();
⋮----
private static async Task<IResult> Enrol(HttpContext http, StubState state, LicenceClock clock)
⋮----
if (StubForce.For(http, state, ErrorSurface.Enrolment) is { } forced)
⋮----
return StubErrors.Refuse(http, forced);
⋮----
return StubErrors.Refuse(http, StubErrors.InvalidRequest);
⋮----
|| !Guid.TryParse(payload.InstallationId, out var installationId)
|| string.IsNullOrWhiteSpace(payload.AppVersion))
⋮----
var licence = StubLicences.Evaluate(payload.Licence, clock);
var (credential, installation) = state.Enrol(installationId, payload.AppVersion, licence);
⋮----
InstallationFilter.WriteQuotaHeaders(http, state.Snapshot(installation), installation.Tier);
⋮----
return Results.Json(
new EnrolmentResponse(credential, installation.Tier, installation.Licence),
⋮----
private static IResult Self(HttpContext http, StubState state)
⋮----
var installation = http.Installation();
⋮----
return Results.Ok(new InstallationResponse(
⋮----
state.Snapshot(installation),
⋮----
private static async Task<IResult> Licence(HttpContext http, StubState state, LicenceClock clock)
⋮----
return StubErrors.Refuse(http, StubErrors.Get(StubErrors.LicenceRejected), reason: licence.State.Reason);
⋮----
state.SetLicence(installation, licence);
⋮----
return Results.Ok(new LicenceUpdateResponse(installation.Tier, installation.Licence));
</file>

<file path="CLAUDE.md">
# CLAUDE.md — Knowledge Fabric AI Gateway (kf-ai-gateway)

Guidance for AI assistants working in this repo.

> **Deeper context:** the decisions this service implements are in the epic
> [knowledgefabric/kf-app#954](https://github.com/KnowledgeFabric/kf-app/issues/954) and,
> once written, ADR D21 in kf-app's `docs/Architecture/AI-Assistant-Architecture.md`. The
> wire contract is `docs/API.md` here. Read both before changing what the gateway exposes.

---

## Project Overview

The **AI Gateway** sits between every Knowledge Fabric installation and the model provider
behind *Knowledge Fabric AI*. It exists so that the application image — which is public on
Docker Hub and must stay so for evaluation — carries **no provider credential**. The gateway
holds that credential, gives each installation an identity of its own, enforces a request rate
limit and a token budget per installation, and forwards chat to the provider.

It is an ASP.NET Core 8 service: minimal APIs throughout, a typed `HttpClient` adapter for
forwarding, the framework rate limiter, EF Core with
PostgreSQL for installations and counters, Application Insights for logs. It runs as an Azure
App Service at `https://ai.knowledgefabric.io`, deployed as a `dotnet publish` package. There is
no service image: the gateway runs in one place, run by us, so a container would buy a
portability it has no use for and make base-image patching ours. This repository publishes no
image at all: kf-app's tests check it out and run the stub from source, so nothing of ours is
published anywhere public and there is no registry credential to hold.

---

## Identity & GitHub Conventions

- Commit under your own `@knowledgefabric.io` identity. Sessions that start from a fresh clone
  default to `Claude <noreply@anthropic.com>` — replace it before the first commit rather than
  letting it reach history:
  ```bash
  git config --local user.name  "Your Name"
  git config --local user.email "you@knowledgefabric.io"
  ```
  To avoid doing this per session, set `GIT_AUTHOR_NAME`/`GIT_AUTHOR_EMAIL` and
  `GIT_COMMITTER_NAME`/`GIT_COMMITTER_EMAIL` in your Claude Code environment settings.
- **Branch off `develop`, and open pull requests back into `develop`.** It is the integration
  branch, what the sandbox deploys, and the repository's **default branch** — which is not
  cosmetic: GitHub closes a ticket on `Closes #N` only when the pull request merges into the
  default branch, and serves `.github/pull_request_template.md` to a new pull request only from
  there. `main` is the release branch and what production deploys, reached by promoting
  `develop`. Neither is committed to directly.
- **Branch names are `feature/{issue}-{summary}` or `fix/{issue}-{summary}`** — the issue number
  first, then a few kebab-cased words: `feature/3-app-service-provisioning`,
  `fix/12-startup-migration-race`. The number is what ties a branch to the ticket that justifies
  it, so work without a ticket gets a ticket rather than a branch. Sessions started by tooling
  default to a `claude/...` name; rename before the first push.
- **Never commit secrets.** The provider key and the connection string are App Service
  application settings, set in the Portal and never written by CI; GitHub holds only the OIDC
  identity that authorises a deploy. Nothing in this repository, its published output or its CI
  logs may carry a credential.
- Pushing to `.github/workflows/` requires a token with the **`workflow`** scope.
- Commit messages must be concise. Do not reference AI tooling in commits or PRs.
- PR descriptions must include two sections, as in kf-app.
  `.github/pull_request_template.md` lays them out, so every PR opens with them already there:
  - **Acceptance criteria** — restate the ticket's acceptance criteria and confirm how each is
    met (or why it is deferred).
  - **Manual testing** — a numbered script a tester who did not write the change can run
    without reading the diff. It states its preconditions — the branch, the exact commands that
    get it running, what has to be up alongside it — and every step pairs an exact action with
    the observable result that proves it: a status code, a header, a field, a log line. "Check
    that enrolment works" is not a step. Cover the refusals as well as the happy path, because
    most of this contract is about what the gateway declines to do, and name the exact
    `X-KF-Error-Code` rather than "an error". Where a step spends something an earlier step
    produced — a credential, an installation id — say which one produced it. Where the behaviour
    can only be seen on the deployed environment, say so and say what to look at there.

    A change with no observable surface at all — a CI workflow, a docs edit — says so in one
    line and names what the reviewer looks at instead: a green run, the rendered page. That is
    the only form "not applicable" takes. A passing automated test is not one: what this section
    buys is a second pair of eyes on the running thing, and the tests were written by whoever
    wrote the bug.

---

## Commands

```bash
dotnet build KnowledgeFabric.AiGateway.sln
dotnet test  KnowledgeFabric.AiGateway.sln
dotnet run --project src/KnowledgeFabric.AiGateway        # http://localhost:5170 (see launchSettings)
docker compose -f docker-compose.postgres.yml up -d        # the local PostgreSQL, and nothing else

dotnet ef migrations add <Name> --project src/KnowledgeFabric.AiGateway --output-dir Data/Migrations
```

The forwarder is configuration: `Forwarding:UpstreamAddress` and `Forwarding:Model` — the
provider, and what the `knowledge-fabric-ai` alias resolves to — plus the provider key, which
keeps the flat name the Portal holds, `AI_GATEWAY_OLLAMA_API_KEY`. As environment variables the
first two are `Forwarding__UpstreamAddress` and `Forwarding__Model`.

Like the connection string they have **no** default in `appsettings.json`: an environment that
names neither gets a process that will not start, rather than one that quietly forwards to
`localhost`. `appsettings.Development.json` points them at a local Ollama, which is what you
develop against; `dotnet test` needs no provider at all, the forwarding tests running against a
fake upstream on a loopback port.

The three timeouts — `Forwarding:ConnectTimeout`, `FirstByteTimeout` and `TotalTimeout` — have
defaults (5s / 45s / 180s) and are validated as a sequence that fits below App Service's 230s
idle timeout. A set that does not fails the process: the platform would answer first, and its
answer carries no `X-KF-Error-Code` and no quota headers.

The database is configuration too, `Database:ConnectionString`, and it has **no** default in
`appsettings.json`: an environment that does not set it gets a process that will not start. The
local address is in `appsettings.Development.json`, so `dotnet run` wants a PostgreSQL on
`localhost:5432` — `docker-compose.postgres.yml` is one — and `dotnet test` wants nothing at all,
the suite running the real pipeline over a SQLite database held in memory, with migration off and
a PostgreSQL connection string that points nowhere. The exception is the startup migration's advisory lock, which cannot be observed
without a server: those tests skip unless `KF_TEST_POSTGRES` names one they may create and drop
databases on, and CI sets it from a service container so they run somewhere rather than nowhere.
Point it at `docker-compose.postgres.yml` to run them locally. A schema change is a migration in the same commit;
`The_migrations_produce_the_current_model` fails when one is missing.

---

## Architecture

### Two surfaces

| Surface | Paths | Caller |
|---|---|---|
| Gateway-native, versioned `/v1` | `/v1/installations`, `/v1/installation`, `/v1/installation/licence` | The application's enrolment client |
| Ollama-native, forwarded | `/api/chat`, `/api/show`, `/api/tags` | The application's existing Ollama connector, unchanged |

The forwarded surface speaks the Ollama native API on purpose (decision D-B): the application
reaches the gateway through the same connector it uses for a customer's own Ollama server — an
address and a bearer token — so nothing new is needed on that side. Everything outside the
two surfaces is refused with `404` because no route matches it.

### Where things go

The solution is `src/KnowledgeFabric.AiGateway` (the service),
`src/KnowledgeFabric.AiGateway.Stub` (G1's in-memory stand-in, below) and a test project for
each. As the tickets land, the service grows these areas, one folder each, named for what the
ticket delivers rather than for a layer:

| Area | Ticket | Owns |
|---|---|---|
| `Forwarding/` | G5 | `/api/chat`: provider key injection, the model alias in both directions, upstream error rewriting, timeouts, token-count capture. Serves `/api/show` and `/api/tags` from the alias rather than forwarding them |
| `Enrolment/` | G4 | `POST /v1/installations`, bearer auth, credential hashing, velocity limits, minimum app version |
| `Quota/` | G6 | Tier policy, request rate limiter, token budget, the `X-KF-*` headers, the global brake |
| `Licensing/` | G7 | `Standard.Licensing` verification against the trusted Knowledge Fabric public keys, tier upgrade and expiry, the AI limits a licence sets over its tier (#28), and the licence tier that chooses that tier's row (#32) |
| `Admin/` | G4/G8 | The status (#37): version, the brake as admission reads it, today's spend against the trailing week as the spend alert reads it (#50), the fleet by served row, the caller's address; list, one by id, revoke, restore, each installation with its allowance and usage and the list filtered and paged (#38); the gateway and tier policy rows read and written, validated at the door, each write — revoke and restore included — logged with the `X-KF-Operator` it names (#39); the licence ids held by more than one installation (#35), shown and never enforced; the daily usage ledger read back, the fleet's days by row or one installation's, and a range's totals and top spenders (#41) |
| `Data/` | G2/G4 | EF Core `DbContext`, migrations, PostgreSQL |
| `Telemetry/` | G8 | OpenTelemetry to Application Insights: the sink where an environment has one, sampling pinned off, the health-check heartbeat dropped, the custom dimensions every request carries for the alerts, and the spend report they compare today against the trailing week with |
| `Usage/` | #41 | The daily usage ledger's in-process half: each installation's requests, refusals and upstream errors per UTC day, counted in memory and written every minute and at shutdown. Tokens are written by `Forwarding/`'s `TokenLedger` as each chat ends |

Until an area exists, do not create its folder: an empty folder is a promise nobody is keeping.

### The stub is part of the contract

`src/KnowledgeFabric.AiGateway.Stub` answers `docs/API.md` from memory, with no provider and no
database, so that kf-app's tests (A2–A6) run against the contract rather than against a mock of
their own. It is not a second implementation of the gateway and must never grow into one: when
a ticket changes what `/v1` or the forwarded surface answers, the change lands in three places
in the same PR — `docs/API.md`, `docs/openapi/gateway-v1.yaml` and the stub — or the two
repositories start believing different things. `ContractDocumentTests` fails when they drift.

Its `/stub/*` control surface (force a refusal, move the tier policy, read the counters, reset)
is deliberately outside the contract: the real gateway has no such paths.

### Configuration and policy are different things

- **Configuration** is what differs per environment: the upstream address, the provider key, the
  connection string, log sinks. It arrives as App Service application settings, which reach the
  process as environment variables. Never compiled in.
- **Policy** is what changes while the service runs: tier allowances, enrolment velocity
  limits, the minimum accepted application version, revocations. It lives in the database and
  changes without a deploy, because the day it matters is the day there is no time for one.

### How it is deployed

**There is one environment, and it answers to two names.** One Azure App Service in West
Europe, deployed from `develop`, with both `ai.knowledgefabric.io` and
`ai-sb.knowledgefabric.io` bound to it. Production is deferred until there is a pilot to justify
it, and until then evaluation installations reach the same service the contract names, so
`docs/API.md`'s compiled base address needs no exception.

Three things follow, and they are the price of that:

- **There is no test environment.** Nowhere is safe to try a risky deploy, a schema change or a
  provider switch: every one of them lands on whatever installations are attached. The word
  "sandbox", and the `stg` in every resource name, no longer mean what they say.
- **A deploy is a restart that drops in-flight streams**, because `deploy.yml` publishes straight
  to the running app. The plan is Premium v3, so deployment slots *are* available — none is
  created, and using one is deferred (#17). So a key rotation is an outage today by choice
  rather than by the platform, and the choice is revisited when installations start depending
  on the service rather than when production is built.
- **`main` has no destination.** Do not promote `develop` to it until production exists;
  `deploy.yml` deploys `develop` and nothing else.

When production is built, `ai.knowledgefabric.io` moves to it — a hostname binds to one App Service at a time, so that cutover has a gap and
belongs before a pilot rather than after. Production runs a **single instance**: the request
rate limiter holds its window in process, so a second instance would silently double every
limit and make `X-KF-Requests-Remaining` a fiction (G6).

Both environments will share one PostgreSQL Flexible Server — Burstable, two databases, `kf_gateway`
and `kf_gateway_sandbox`, a login per database with no access to the other — `kf_gateway`
exists and is unused until production does. Sharing is a cost decision carrying two standing
consequences. A point-in-time restore acts on the **server**, so
recovering one database rolls the other back on the restored copy and only the intended one may
be repointed. And the CPU credits are shared, so a sandbox load test can throttle production —
before the first customer installation, split the servers or leave Burstable. Backups are kept
35 days, locally: losing the installations table costs every installation a re-enrolment, which
is survivable, and no prompt or response was ever in there to lose.

The schema migrates at startup, in every environment, before Kestrel opens (`DatabaseMigrator`).
Two rules follow from that, and neither is optional:

- **Migrations are expand/contract.** Add nullable columns and new tables, backfill, and drop
  only in a later release once no running version references the old shape. A slot swap runs the
  new version's migration against the database the old version is still serving.
- **Migrating takes an advisory lock.** Both slots can boot at once and EF Core does not
  serialise `MigrateAsync` by itself.

---

## Invariants

These hold across every ticket. A change that breaks one is a decision to be taken in the epic,
not a line in a PR.

1. **No credential in the deployed artifact.** The provider key exists only as an App Service
   application setting, configured in the Portal: never compiled in, never in a committed file,
   and never in a CI log because **the deploy ships code and never carries it** — a key that
   does not reach a runner cannot leak from one. What this protects is kf-app's public
   Docker Hub image — this service exists so that image holds nothing worth taking, and an
   artifact of ours that carried the key would recreate kf-app#817 one hop away. The stub holds
   no key by construction: it forwards to nothing.
2. **No body logging.** A prompt or a response is never written to a log, a database row, a
   metric label or an error message. Metadata only: installation id, token counts, timings,
   status. G5 makes this a test — a request carrying a sentinel string must leave it nowhere —
   and every later ticket keeps that test green. It is what lets the application's privacy
   claim say the gateway keeps no content.
3. **Nothing upstream leaks.** No upstream hostname, model name, key fragment or vendor error
   text reaches a response body or header. The one model the gateway advertises is the alias
   `knowledge-fabric-ai`; the application never learns what it maps to (kf-app's ADR D15).
   The alias outlives the provider: a different backend is a new adapter behind the same wire
   shape, never a different surface for the application to learn.
4. **The allow-list is the contract.** `/api/chat`, `/api/show` and `/api/tags` are the whole
   of it, and only `/api/chat` is *forwarded*: the other two are **served by the gateway** from
   the alias, because their contracted answers are constants and a passthrough would be a leak
   that has to be prevented afresh on every provider, forever. Adding a path is a change to
   `docs/API.md` and to kf-app, never a route quietly added beside the three in
   `ForwardingEndpoints`. `/api/generate` and `/api/embeddings` stay refused: there is no vector
   store and no completion surface in the product.

   The allow-list runs in the other direction too, and for the same reason. **No response header
   of the provider's is copied**, and a chat chunk is **rebuilt from the fields the contract
   publishes** rather than stripped of known offenders — a deny-list would have to be re-audited
   against every provider and every provider's next release, and the audit that gets skipped is
   the one that leaks.
5. **Admission is decided at the start.** A request that was admitted completes even if it
   crosses a limit mid-stream. Refusals are `429` with `X-KF-Error-Code` and `Retry-After`.
6. **The contract is versioned and additive.** Changes to `/v1` add fields; they do not rename
   or remove. A breaking change is `/v2` beside `/v1`. Gateway changes deploy before the
   application changes that need them.
7. **Every installation is its own blast radius.** Limits, budgets and revocation are per
   installation. Nothing an abuser does may take the service from anyone else; the global
   brake exists for the provider's sake, not as a substitute for that.

---

## Coding Conventions

- `Directory.Build.props` turns on nullable reference types, implicit usings and
  warnings-as-errors for every project. Fix the warning; do not suppress it.
- **Prefer `async`/`await`** throughout. No `.Result`/`.Wait()`.
- **Comments explain *why*, not *what*.** Mechanics — thresholds, evaluation order, formulae —
  go in XML documentation on the code that carries them. Decisions go in the epic or an ADR.
- Minimal APIs, not controllers. Endpoint groups per area (`/v1/...`, `/api/...`).
- Configuration binds to options classes validated at startup (`ValidateOnStart`); a missing
  upstream address fails the process, not the first request.

### Testing

Every test method (`[Fact]`/`[Theory]`) must have a one-line comment directly above its
attribute stating *what it verifies and why* — which boundary, regression or invariant it
exists for — not a restatement of the method name. `tests/.../GatewayEndpointTests.cs` is the
reference. Behaviour tests run the real pipeline through `WebApplicationFactory<Program>`;
forwarding tests use a fake upstream, never a live provider. Anything clock-dependent (windows,
budgets, expiry) takes a `TimeProvider`.

**A test that asserts the service *refuses to start* is the exception, and must build and start its
own host.** `WebApplicationFactory` cannot call top-level statements, so it runs the entry point on
a background thread; a startup failure there disposes the service provider while the test thread is
still resolving from it, and the caller gets an `ObjectDisposedException` instead of the real
exception often enough to matter. `DatabaseStartupTests` shows the shape: precise assertions on a
host the test starts, plus one test through the factory asking only *whether* startup failed, which
is the one question the race cannot answer two ways.

---

## Key Files

| File | Purpose |
|---|---|
| `src/KnowledgeFabric.AiGateway/Program.cs` | Composition: health, the middleware order, and the surfaces mapped in it |
| `src/KnowledgeFabric.AiGateway/Forwarding/` | The forwarded surface: the alias, the chunk and header allow-lists, the timeouts, and `IChatAdapter` — the seam a change of provider goes behind |
| `src/KnowledgeFabric.AiGateway/Licensing/` | Licence verification (G7): the compiled-in trusted keys, kf-app's list key for key, and the contract's algorithm with its reasons mapped onto docs/API.md's two. `LicenceLimits` is `ai.tokens`, `ai.period` and `ai.rpm`, laid per request by `PolicyStore` over the `standard` or `enterprise` row the licence's `tier` chooses (#32) |
| `tests/KnowledgeFabric.AiGateway.Tests/LicenceContract/` | A copy of kf-admin's contract fixtures, asserted by `LicenceContractTests`; refresh it when kf-admin regenerates the set |
| `src/KnowledgeFabric.AiGateway.Stub/` | The contract answered in memory, for kf-app's tests (G1) |
| `tests/KnowledgeFabric.AiGateway.Tests/GatewayEndpointTests.cs` | Reference tests: readiness and the allow-list |
| `docs/API.md` | The wire contract both repositories build against |
| `docs/openapi/gateway-v1.yaml` | The same `/v1` surface as OpenAPI, for generators and reviewers |
| `docs/Admin.md` | The operator surface, deliberately outside the contract and what kf-admin's console builds against: the two admin tokens and which to give whom, the status, list/revoke/restore, what to do about a licence on more than one installation, reading and changing policy with the rules a write is refused by, the audit line every write leaves and the `X-KF-Operator` it names, the usage history and what a restart costs it, and the `psql` fallback |
| `docs/Provisioning-Environments.md` | How an environment is built: the shared database, the App Service, DNS and TLS, OIDC federated credentials, and what sharing one PostgreSQL server costs |
| `src/KnowledgeFabric.AiGateway/Data/` | The schema: `Installation`, `DailyUsage` and the portable write that adds to a day, the context, the options validated at startup, the migration run before the first request |
| `src/KnowledgeFabric.AiGateway/Telemetry/` | Where metadata leaves the process: the Azure Monitor distro wired only when a connection string is configured, sampling off by decision, a passing `/health` dropped before it is billed, `SpanTags` — the dimension names `docs/Runbook.md`'s queries filter on — and `SpendReport`, the quarter-hourly line the spend alert reads and the silence alert listens for |
| `docs/Runbook.md` | The alerts (G8): each one's query and thresholds, what it means and what to do when it fires, the abuse procedures that pull `docs/Admin.md`'s levers, rotating the provider key (planned, after a leak, and once there is a slot), and the queries for the figures G8 names. Creating the rules and making each fire is `docs/Provisioning-Environments.md` §B7 |
| `docker-compose.postgres.yml` | A local PostgreSQL and nothing else; the gateway itself runs with `dotnet run` |
| `.github/workflows/ci.yml` | Build and test on every PR and on `main`/`develop` |
| `.github/workflows/deploy.yml` | `develop` deploys the one environment, through `_deploy-environment.yml`. Ships code only — settings live in App Service. There is no production job until there is a production |
| `VERSION` | Single source of truth for the service version. `Directory.Build.props` stamps it into the assembly, the SDK appends the commit, and `GET /admin/status` reports the two |
</file>

<file path="docker-compose.postgres.yml">
services:
  db:
    image: postgres:16-alpine
    ports:
      - "5432:5432"
    environment:
      POSTGRES_DB: kf_ai_gateway
      POSTGRES_USER: kf_ai_gateway
      POSTGRES_PASSWORD: kf_ai_gateway
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U kf_ai_gateway -d kf_ai_gateway"]
      interval: 5s
      timeout: 3s
      retries: 12
    volumes:
      - gateway-db:/var/lib/postgresql/data
volumes:
  gateway-db:
</file>

<file path="README.md">
# Knowledge Fabric AI Gateway

The service that stands between every Knowledge Fabric installation and the model provider
behind **Knowledge Fabric AI**. It holds the provider credential so that the public application
image does not, gives each installation an identity, and enforces a request rate limit and a
token budget per installation.

Why it exists, what was decided and in what order the work lands:
[Epic — Knowledge Fabric AI Gateway](https://github.com/KnowledgeFabric/kf-app/issues/954).
The wire contract is [`docs/API.md`](docs/API.md).

## Status

Contract (G1) on a skeleton (G2). The wire contract is written, published as OpenAPI, and
answered in memory by a stub kf-app's tests run against. The service itself builds, answers
`/health`, forwards the three Ollama paths to a configured upstream, and carries its schema —
installations and their counters — on PostgreSQL, migrated on the way up. Enrolment, quotas, the
licensed tier and observability are the open tickets listed on the epic.

## Run it

```bash
dotnet test  KnowledgeFabric.AiGateway.sln
dotnet run --project src/KnowledgeFabric.AiGateway
curl -i http://localhost:5170/health
```

`dotnet test` needs nothing installed: the suite runs the real pipeline without a database.
`dotnet run` does need a PostgreSQL — the service migrates its schema at startup and will not
start without one it can reach. `docker-compose.postgres.yml` is that database and nothing else,
with the credentials `appsettings.Development.json` expects:

```bash
docker compose -f docker-compose.postgres.yml up -d
```

## The stub

`src/KnowledgeFabric.AiGateway.Stub` answers the contract from memory: it issues credentials,
counts a quota, refuses on demand and returns a canned chat, with no provider and no database
behind it. It exists so kf-app's tests run against the contract rather than a mock of their own.

```bash
dotnet run --project src/KnowledgeFabric.AiGateway.Stub          # http://localhost:5080
```

kf-app's tests run it the same way, from a checkout of this repository. There is no published
image: an artefact of ours on a public registry is a thing to keep patched and a credential to
keep, and a checkout inside the organisation needs neither.

Every switch it offers — force any refusal in the contract, move a tier's allowance, read the
counters, reset — is in [`docs/API.md`](docs/API.md#the-stub-gateway). It must never be
deployed anywhere a real installation can reach it.

## Configuration

Everything that differs per environment is an App Service application setting, which reaches
the process as an environment variable — never compiled in:

| Variable | Meaning |
|---|---|
| `Forwarding__UpstreamAddress` | The provider the gateway forwards chat to. **Required**: no default outside Development, so an environment that does not set it fails to start rather than quietly forwarding to `localhost`. |
| `Forwarding__Model` | What the `knowledge-fabric-ai` alias resolves to. **Required**, and it reaches no response body or header — the application never learns it. |
| `AI_GATEWAY_OLLAMA_API_KEY` | The provider key, injected as the upstream bearer token. Absent is valid: a local Ollama wants none. |
| `Forwarding__ConnectTimeout`, `Forwarding__FirstByteTimeout`, `Forwarding__TotalTimeout` | Defaults `00:00:05` / `00:00:45` / `00:03:00`. Validated as a sequence that fits below App Service's 230s idle timeout; a set that does not fails the process. |
| `Database__ConnectionString` | PostgreSQL. **Required**: there is no default outside Development, and an environment that does not set it gets a process that refuses to start rather than one that fails on the first enrolment. |
| `Database__MigrateOnStartup` | Whether to bring the schema up to date before serving. Default `true`. |

None of them is ever compiled in. The log sink joins them where an environment has one
(`APPLICATIONINSIGHTS_CONNECTION_STRING`, G8); absent is valid and means no telemetry sink.

## What it exposes

| Surface | Paths |
|---|---|
| Gateway-native, versioned | `POST /v1/installations`, `GET /v1/installation`, `PUT /v1/installation/licence` |
| Ollama-native, forwarded | `POST /api/chat`, `POST /api/show`, `GET /api/tags` |

Everything else is refused. An installation must be able to reach `ai.knowledgefabric.io` over
HTTPS; a customer's own Ollama server remains the fully offline option in the application.

## Working here

The contract is [`docs/API.md`](docs/API.md), with the `/v1` surface also as OpenAPI in
[`docs/openapi/gateway-v1.yaml`](docs/openapi/gateway-v1.yaml). Read [`CLAUDE.md`](CLAUDE.md) first — it carries the invariants (no credential in the deployed artifact,
no body logging, nothing upstream leaks, the allow-list is the contract) and the conventions.
</file>

<file path="VERSION">
0.1.0
</file>

</files>
