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, .gitignore, .gitattributes, **/*.key, **/*.lic, **/*.yaml, **/*.yml, docs/openapi/**, src/**/Migrations/**, docs/**/*.md
- 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>
src/
  KnowledgeFabric.AiGateway/
    Admin/
      AdminAllowance.cs
      AdminAudit.cs
      AdminBody.cs
      AdminEndpoints.cs
      AdminLocation.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
    Location/
      AddressFiles.cs
      CloudRanges.cs
      InstallationLocation.cs
      InstallationLocator.cs
      LocationDownloads.cs
      LocationFiles.cs
      LocationOptions.cs
      LocationRefresh.cs
      LocationServiceCollectionExtensions.cs
      PublicAddress.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
README.md
VERSION
</directory_structure>

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

<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),
⋮----
AdminLocation.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/AdminLocation.cs">
public static AdminLocation? Of(Installation installation) =>
⋮----
? new AdminLocation(
⋮----
installation.NetworkAsn is { } asn ? new AdminNetwork(asn, installation.NetworkName) : null,
installation.Cloud is { } provider ? new AdminCloud(CloudWords.Of(provider), installation.CloudRegion) : null,
⋮----
public static class CloudWords
⋮----
public static string Of(CloudProvider provider) => provider.ToString().ToLowerInvariant();
</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, row.Country })
.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),
⋮----
.Where(group => group.Country is not null)
.GroupBy(group => group.Country!)
.Select(country => (Code: country.Key, Count: country.Sum(group => group.Count)))
.OrderByDescending(country => country.Count)
.ThenBy(country => country.Code, StringComparer.Ordinal)
.ToDictionary(country => country.Code, country => country.Count),
Unlocated: active.Where(group => group.Country is 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);
⋮----
installation.Property(i => i.Country).HasMaxLength(2);
installation.Property(i => i.NetworkName).HasMaxLength(InstallationLocator.NetworkNameLength);
installation.Property(i => i.Cloud).HasConversion(ContractWords<CloudProvider>()).HasMaxLength(16);
installation.Property(i => i.CloudRegion).HasMaxLength(InstallationLocator.RegionLength);
⋮----
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);
⋮----
locator.Locate(address)?.ApplyTo(installation, now);
⋮----
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);
locator.Locate(http)?.ApplyTo(installation, clock.GetUtcNow());
⋮----
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();
⋮----
var stamp = database.Installations.Where(row => row.Id == installation.Id);
⋮----
if (locator.Locate(Context) is { } location)
⋮----
location.ApplyTo(installation, now);
⋮----
await stamp.ExecuteUpdateAsync(
⋮----
.SetProperty(row => row.LastSeenAt, now)
.SetProperty(row => row.Country, installation.Country)
.SetProperty(row => row.NetworkAsn, installation.NetworkAsn)
.SetProperty(row => row.NetworkName, installation.NetworkName)
.SetProperty(row => row.Cloud, installation.Cloud)
.SetProperty(row => row.CloudRegion, installation.CloudRegion)
.SetProperty(row => row.LocatedAt, installation.LocatedAt),
⋮----
await stamp.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/Location/AddressFiles.cs">
public sealed class CountryFile
⋮----
private readonly Reader _reader;
⋮----
public static CountryFile Load(byte[] mmdb)
⋮----
var reader = new Reader(new MemoryStream(mmdb, writable: false));
var file = new CountryFile(reader, Mmdb.BuiltAt(reader));
⋮----
return file.Find(LocationFiles.KnownAddress) is not null
⋮----
: throw new InvalidDataException("The country file places no country on a well-known public address.");
⋮----
public string? Find(IPAddress address) => _reader.Find<CountryRecord>(address)?.Country?.IsoCode;
⋮----
public sealed class NetworkFile
⋮----
public static NetworkFile Load(byte[] mmdb)
⋮----
var file = new NetworkFile(reader, Mmdb.BuiltAt(reader));
⋮----
: throw new InvalidDataException("The network file names no autonomous system for a well-known public address.");
⋮----
public InstallationNetwork? Find(IPAddress address) =>
⋮----
? new InstallationNetwork(number, string.IsNullOrWhiteSpace(record.Organisation) ? null : record.Organisation.Trim())
⋮----
internal static class Mmdb
⋮----
public static DateTimeOffset BuiltAt(Reader reader) =>
new(DateTime.SpecifyKind(reader.Metadata.BuildDate, DateTimeKind.Utc));
⋮----
internal sealed class CountryRecord
⋮----
internal sealed class CountryName
⋮----
internal sealed class NetworkRecord
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/CloudRanges.cs">
public static CloudRange? Parse(string? prefix, InstallationCloud cloud)
⋮----
|| !IPAddress.TryParse(prefix.AsSpan(0, slash), out var network)
|| !int.TryParse(prefix.AsSpan(slash + 1), NumberStyles.None, CultureInfo.InvariantCulture, out var length)
⋮----
return new CloudRange(network, length, cloud);
⋮----
public sealed class CloudRanges
⋮----
public static readonly CloudRanges Empty = new([]);
⋮----
var ipv4 = new SortedSet<int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
var ipv6 = new SortedSet<int>(Comparer<int>.Create((a, b) => b.CompareTo(a)));
⋮----
if (_ranges.TryGetValue(key, out var existing) && (existing.Region is not null || range.Cloud.Region is null))
⋮----
(width == 32 ? ipv4 : ipv6).Add(range.PrefixLength);
⋮----
public InstallationCloud? Find(IPAddress address)
⋮----
address = address.MapToIPv4();
⋮----
if (_ranges.TryGetValue((Length(length, width), bits & Mask(length, width)), out var cloud))
⋮----
public static IEnumerable<CloudRange> FromAws(JsonDocument document)
⋮----
if (!root.TryGetProperty(list, out var entries) || entries.ValueKind != JsonValueKind.Array)
⋮----
foreach (var entry in entries.EnumerateArray())
⋮----
var cloud = new InstallationCloud(
⋮----
string.Equals(region, "GLOBAL", StringComparison.OrdinalIgnoreCase) ? null : region);
⋮----
if (CloudRange.Parse(Text(entry, field), cloud) is { } range)
⋮----
public static IEnumerable<CloudRange> FromGcp(JsonDocument document)
⋮----
if (!document.RootElement.TryGetProperty("prefixes", out var entries) || entries.ValueKind != JsonValueKind.Array)
⋮----
var cloud = new InstallationCloud(CloudProvider.Gcp, Text(entry, "scope"));
⋮----
if (CloudRange.Parse(Text(entry, "ipv4Prefix") ?? Text(entry, "ipv6Prefix"), cloud) is { } range)
⋮----
public static IEnumerable<CloudRange> FromAzure(JsonDocument document)
⋮----
if (!document.RootElement.TryGetProperty("values", out var tags) || tags.ValueKind != JsonValueKind.Array)
⋮----
foreach (var tag in tags.EnumerateArray())
⋮----
|| !name.StartsWith("AzureCloud.", StringComparison.Ordinal)
|| !tag.TryGetProperty("properties", out var properties)
⋮----
|| !properties.TryGetProperty("addressPrefixes", out var prefixes)
⋮----
var cloud = new InstallationCloud(CloudProvider.Azure, region);
⋮----
foreach (var prefix in prefixes.EnumerateArray())
⋮----
if (prefix.ValueKind == JsonValueKind.String && CloudRange.Parse(prefix.GetString(), cloud) is { } range)
⋮----
private static string? Text(JsonElement element, string name) =>
⋮----
&& element.TryGetProperty(name, out var value)
⋮----
? value.GetString()
⋮----
private static (UInt128 Bits, int Width) Bits(IPAddress address)
⋮----
address.TryWriteBytes(bytes, out var written);
⋮----
? (BinaryPrimitives.ReadUInt32BigEndian(bytes), 32)
: (BinaryPrimitives.ReadUInt128BigEndian(bytes), 128);
⋮----
private static UInt128 Mask(int length, int width) =>
⋮----
private static int Length(int length, int width) => width == 32 ? length : 1000 + length;
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/InstallationLocation.cs">
public void ApplyTo(Installation installation, DateTimeOffset now)
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/InstallationLocator.cs">
public sealed class InstallationLocator(ILocationData data, ILogger<InstallationLocator> logger)
⋮----
public InstallationLocation? Locate(HttpContext http) => Locate(ClientAddress.Of(http));
⋮----
public InstallationLocation? Locate(string address)
⋮----
if (!PublicAddress.TryRead(address, out var ip))
⋮----
found = data.Find(ip);
⋮----
logger.LogWarning(
⋮----
exception.GetType().Name);
⋮----
private static InstallationLocation? Fitted(InstallationLocation found)
⋮----
var country = found.Country.Trim().ToUpperInvariant();
⋮----
if (country.Length != 2 || !char.IsAsciiLetterUpper(country[0]) || !char.IsAsciiLetterUpper(country[1]) || country == "ZZ")
⋮----
return new InstallationLocation(country, network, cloud);
⋮----
private static string? Cut(string? text, int length) =>
string.IsNullOrWhiteSpace(text) ? null : text.Length <= length ? text : text[..length];
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/LocationDownloads.cs">
public sealed partial class LocationDownloads(IHttpClientFactory clients)
⋮----
public static readonly Uri DbIp = new("https://download.db-ip.com/free/");
⋮----
public static readonly Uri AwsRanges = new("https://ip-ranges.amazonaws.com/ip-ranges.json");
⋮----
public static readonly Uri GcpRanges = new("https://www.gstatic.com/ipranges/cloud.json");
⋮----
public static readonly Uri AzureServiceTagsPage = new("https://www.microsoft.com/en-us/download/details.aspx?id=56519");
⋮----
private static partial Regex ServiceTagsLink();
⋮----
public async Task<CountryFile> CountriesAsync(DateTimeOffset now, CancellationToken cancellationToken) =>
CountryFile.Load(await DbIpAsync("dbip-country-lite", now, cancellationToken));
⋮----
public async Task<NetworkFile> NetworksAsync(DateTimeOffset now, CancellationToken cancellationToken) =>
NetworkFile.Load(await DbIpAsync("dbip-asn-lite", now, cancellationToken));
⋮----
public Task<IReadOnlyList<CloudRange>> AwsAsync(CancellationToken cancellationToken) =>
⋮----
public Task<IReadOnlyList<CloudRange>> GcpAsync(CancellationToken cancellationToken) =>
⋮----
public async Task<IReadOnlyList<CloudRange>> AzureAsync(CancellationToken cancellationToken)
⋮----
var page = await Client().GetStringAsync(AzureServiceTagsPage, cancellationToken);
⋮----
?? throw new InvalidDataException("The Service Tags page links no Service Tags file; its layout may have changed.");
⋮----
public static Uri? NewestServiceTags(string page) =>
ServiceTagsLink().Matches(page)
.OrderByDescending(match => match.Groups["date"].Value, StringComparer.Ordinal)
.Select(match => new Uri(match.Value))
.FirstOrDefault();
⋮----
public static IReadOnlyList<Uri> DbIpFiles(string name, DateTimeOffset now)
⋮----
var month = new DateTimeOffset(now.UtcDateTime.Year, now.UtcDateTime.Month, 1, 0, 0, 0, TimeSpan.Zero);
⋮----
new Uri(DbIp, $"{name}-{month.ToString("yyyy-MM", CultureInfo.InvariantCulture)}.mmdb.gz"),
new Uri(DbIp, $"{name}-{month.AddMonths(-1).ToString("yyyy-MM", CultureInfo.InvariantCulture)}.mmdb.gz"),
⋮----
private async Task<byte[]> DbIpAsync(string name, DateTimeOffset now, CancellationToken cancellationToken)
⋮----
using var response = await client.GetAsync(file, HttpCompletionOption.ResponseHeadersRead, cancellationToken);
⋮----
response.EnsureSuccessStatusCode();
⋮----
await using var compressed = await response.Content.ReadAsStreamAsync(cancellationToken);
await using var gzip = new GZipStream(compressed, CompressionMode.Decompress);
⋮----
throw new InvalidOperationException("Unreachable: the last file either answers or throws.");
⋮----
private async Task<IReadOnlyList<CloudRange>> RangesAsync(
⋮----
await using var body = await Client().GetStreamAsync(file, cancellationToken);
using var document = await JsonDocument.ParseAsync(body, cancellationToken: cancellationToken);
⋮----
var ranges = read(document).ToList();
⋮----
: throw new InvalidDataException($"{file.Host} answered with no ranges the gateway can read.");
⋮----
private static async Task<byte[]> ReadBoundedAsync(Stream source, CancellationToken cancellationToken)
⋮----
using var buffer = new MemoryStream();
⋮----
while ((read = await source.ReadAsync(chunk, cancellationToken)) > 0)
⋮----
throw new InvalidDataException("A lookup file decompressed past the size the gateway accepts.");
⋮----
buffer.Write(chunk, 0, read);
⋮----
return buffer.ToArray();
⋮----
private HttpClient Client() => clients.CreateClient(ClientName);
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/LocationFiles.cs">
public interface ILocationData
⋮----
InstallationLocation? Find(IPAddress address);
⋮----
public static readonly LocationSnapshot Empty = new(null, null, new Dictionary<CloudProvider, IReadOnlyList<CloudRange>>());
⋮----
: new CloudRanges(Clouds.OrderBy(cloud => cloud.Key).SelectMany(cloud => cloud.Value));
⋮----
public sealed class LocationFiles : ILocationData
⋮----
public static readonly IPAddress KnownAddress = IPAddress.Parse("8.8.8.8");
⋮----
private volatile LocationSnapshot _current = LocationSnapshot.Empty;
⋮----
public void Publish(LocationSnapshot snapshot) => _current = snapshot;
⋮----
public InstallationLocation? Find(IPAddress address)
⋮----
? new InstallationLocation(country, files.Networks?.Find(address), files.Ranges.Find(address))
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/LocationOptions.cs">
public sealed class LocationOptions
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/LocationRefresh.cs">
public sealed class LocationRefresh(
⋮----
ILogger<LocationRefresh> logger) : BackgroundService
⋮----
public static readonly TimeSpan Interval = TimeSpan.FromDays(7);
⋮----
public static readonly TimeSpan Retry = TimeSpan.FromHours(1);
⋮----
Enum.GetValues<LocationSource>().ToDictionary(source => source, _ => DateTimeOffset.MinValue);
⋮----
private readonly SemaphoreSlim _refreshing = new(1, 1);
⋮----
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
⋮----
logger.LogInformation(
⋮----
await Task.Yield();
⋮----
using var timer = new PeriodicTimer(Retry, clock);
⋮----
while (await timer.WaitForNextTickAsync(stoppingToken))
⋮----
public async Task RefreshAsync(CancellationToken cancellationToken)
⋮----
await _refreshing.WaitAsync(cancellationToken);
⋮----
var now = clock.GetUtcNow();
⋮----
countries = await downloads.CountriesAsync(now, cancellationToken);
⋮----
networks = await downloads.NetworksAsync(now, cancellationToken);
⋮----
clouds[CloudProvider.Aws] = await downloads.AwsAsync(cancellationToken);
⋮----
clouds[CloudProvider.Gcp] = await downloads.GcpAsync(cancellationToken);
⋮----
clouds[CloudProvider.Azure] = await downloads.AzureAsync(cancellationToken);
⋮----
logger.LogWarning(
⋮----
files.Publish(new LocationSnapshot(countries, networks, clouds));
⋮----
_refreshing.Release();
⋮----
private void Loaded(LocationSource source, string detail) =>
logger.LogInformation("Loaded the {Source} location file: {Detail}.", source, detail);
⋮----
private static bool Held(LocationSource source, LocationSnapshot current) => source switch
⋮----
LocationSource.Aws => current.Clouds.ContainsKey(CloudProvider.Aws),
LocationSource.Gcp => current.Clouds.ContainsKey(CloudProvider.Gcp),
LocationSource.Azure => current.Clouds.ContainsKey(CloudProvider.Azure),
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/LocationServiceCollectionExtensions.cs">
public static class LocationServiceCollectionExtensions
⋮----
public static IServiceCollection AddInstallationLocation(this IServiceCollection services, IConfiguration configuration)
⋮----
.Bind(configuration.GetSection(LocationOptions.SectionName))
.ValidateOnStart();
⋮----
services.AddHttpClient(LocationDownloads.ClientName, client =>
⋮----
client.DefaultRequestHeaders.UserAgent.ParseAdd("kf-ai-gateway");
client.Timeout = TimeSpan.FromMinutes(5);
⋮----
services.AddHostedService(provider => provider.GetRequiredService<LocationRefresh>());
</file>

<file path="src/KnowledgeFabric.AiGateway/Location/PublicAddress.cs">
public static class PublicAddress
⋮----
IPNetwork.Parse("0.0.0.0/8"),
IPNetwork.Parse("10.0.0.0/8"),
IPNetwork.Parse("100.64.0.0/10"),
IPNetwork.Parse("127.0.0.0/8"),
IPNetwork.Parse("169.254.0.0/16"),
IPNetwork.Parse("172.16.0.0/12"),
IPNetwork.Parse("192.0.0.0/24"),
IPNetwork.Parse("192.0.2.0/24"),
IPNetwork.Parse("192.168.0.0/16"),
IPNetwork.Parse("198.18.0.0/15"),
IPNetwork.Parse("198.51.100.0/24"),
IPNetwork.Parse("203.0.113.0/24"),
IPNetwork.Parse("224.0.0.0/4"),
IPNetwork.Parse("240.0.0.0/4"),
⋮----
IPNetwork.Parse("::/8"),
IPNetwork.Parse("64:ff9b::/96"),
IPNetwork.Parse("100::/64"),
IPNetwork.Parse("2001:db8::/32"),
IPNetwork.Parse("fc00::/7"),
IPNetwork.Parse("fe80::/10"),
IPNetwork.Parse("fec0::/10"),
IPNetwork.Parse("ff00::/8"),
⋮----
public static bool TryRead(string? text, out IPAddress address)
⋮----
if (!IPAddress.TryParse(text, out var parsed))
⋮----
parsed = parsed.MapToIPv4();
⋮----
if (NotPublic.Any(range => range.Contains(parsed)))
</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.AddInstallationLocation(builder.Configuration);
⋮----
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 location lookup files (#55) need no configuration: the gateway fetches them itself, in the
background, from publishers that need no account or key. `Location:Fetch=false` turns that off,
and every test host sets it, because a test resolves addresses against `FixedLocations` and never
downloads. A new factory that starts `Program` sets it too.

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 and by country (#55), the caller's address; list, one by id, revoke, restore, each installation with its allowance and usage, where it last called from (#55), 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 |
| `Location/` | #55 | Where each installation calls from: the caller's address resolved in process to a country and a network (DB-IP Lite, MMDB) and a cloud region (AWS, Google and Azure's published ranges), the files fetched in the background and held in memory, and the address itself never stored, logged or sent. Written at enrolment, on installing a licence and on the last-seen stamp; reported only on `/admin` |
| `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, where each installation calls from with the files it is resolved against, their attribution and the step-zero check of the caller's address, 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 |
| `src/KnowledgeFabric.AiGateway/Location/` | Where installations call from (#55): `PublicAddress` (what is worth looking up), `InstallationLocator` (what may be stored, and never the address), `LocationFiles` and `LocationRefresh` (the files, fetched in the background and swapped in whole), `CloudRanges` (the three providers' lists, longest prefix first). Tests resolve against `FixedLocations`, never a download |
| `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="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>
