Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/degraded-backend-boot.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": minor
---

Keep working backends available when a secondary backend fails boot validation, and report invalid subscription mint dates as unknown expiry.
11 changes: 10 additions & 1 deletion api-report/ui-server.txt
Original file line number Diff line number Diff line change
Expand Up @@ -242,6 +242,15 @@ signatures (every public export and the types it is made of)
export type AwaitableActivityStore = Omit<ActivityStore, ActivityWriteMethod> & {
[K in ActivityWriteMethod]: (...args: Parameters<ActivityStore[K]>) => Awaitable<ReturnType<ActivityStore[K]>>;
};
BackendBootFailure (packages/ui-server/src/agent/backend.ts)
export interface BackendBootFailure {
backendId: string;
phase: "resolution" | "runtime";
site: "assertBackendResolvable" | "probeBackendRuntimes";
errorClass: string;
message: string;
at: string;
}
BackendRegistry (packages/ui-server/src/agent/backend.ts)
export interface BackendRegistry {
getBackends(): Promise<AgentBackend[]>;
Expand Down Expand Up @@ -2379,7 +2388,7 @@ signatures (every public export and the types it is made of)
turn_usd: z.ZodNumber;
}, z.core.$strict>;
assertBackendResolvable (packages/ui-server/src/agent/backend.ts)
export function assertBackendResolvable(agent: AgentConfig, resolve?: (specifier: string) => void, load?: (specifier: string) => unknown): void;
export function assertBackendResolvable(agent: AgentConfig, resolve?: (specifier: string) => void, load?: (specifier: string) => unknown): BackendBootFailure[];
attribution (packages/ui-server/src/governance/events.ts)
const attribution: z.ZodObject<{
actor: z.ZodEnum<{
Expand Down
23 changes: 15 additions & 8 deletions docs/decisions/claude-code-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ next to it.
`packages/ui-server/src/config/env.ts:584-584`) and is null when unset
(`claudeCodePath`, `packages/ui-server/src/config/env.ts:1200`). The whole `agent` block is copied into the backend's module
config (`config: { ...agent }`,
`packages/ui-server/src/agent/backend.ts:505`), read back as a string
`packages/ui-server/src/agent/backend.ts:532`), read back as a string
(`const claudeCodePath`, `packages/ui-backend-claude/src/module.ts:266-270`)
and handed to the SDK (`backend.claudeCodePath`,
`packages/ui-backend-claude/src/sdk-options.ts:385`). Because of the `||`
Expand Down Expand Up @@ -210,9 +210,9 @@ unnecessary.
installed but cannot run — a musl binary with no musl loader — it fails with
"exists but failed to launch". Both strings are in
`node_modules/@anthropic-ai/claude-agent-sdk/sdk.mjs`. The boot probe below
turns either into a refusal to start, for the same reason a missing backend
refuses to boot (`A missing (or unrecognized) agent backend`,
`packages/ui-server/src/app.ts:416-421`).
refuses startup when either failure affects the default backend. Since
#3817, a failed secondary backend is excluded while the working default
continues; health reports degraded and authenticated status retains the cause.
- **The published range is still a caret, and that bounds what this repo can
guarantee.** `@schlessera/brain-backend-claude` depends on `^0.3.241`, and a
host resolves it in its own lockfile. A host can bump the SDK — and so the
Expand Down Expand Up @@ -259,15 +259,18 @@ than refuses on a mismatch.**
the same exec wrapper and environment a turn uses, so a binary the agent's
uid cannot execute fails here and not on the first turn.
- **What boot does with the answer.** A missing binary, or one that will not
run `--version`: **refuse to start**. A pair other than the measured one: one
run `--version`: **refuse the default backend at boot; exclude a secondary
backend and report degraded health** (#3817). Explicit incompatible version
requirements receive the same containment; that backend never executes.
A pair other than the measured one: one
warning naming both pairs, and boot continues. A clean `--version` shows the
binary launches, not that a session works; the first turn's `init` is the
first proof of that.
- **Where it shows.** `/api/status`, which is behind the auth guard and already
reports the source commit (`Operational status`,
`packages/ui-server/src/routes/health.ts:57-75`), and the run record. Not
`packages/ui-server/src/routes/health.ts:61-79`), and the run record. Not
`/api/health`: it is public and deliberately carries no version
(`Public liveness probe`, `health.ts:14-16`). Not `brain doctor`: it runs on
(`Public liveness probe`, `health.ts:15-17`). Not `brain doctor`: it runs on
the user's machine against a different binary.

Why warn rather than refuse an unmeasured pair, given that what was measured is
Expand Down Expand Up @@ -692,7 +695,11 @@ subscription authenticates.
server's part: the operator records the mint date
(`BRAIN_UI_CLAUDE_TOKEN_MINTED_AT`), the server warns from 30 days before
the measured one-year expiry, and `/api/status` shows when the token last
worked. Every auth failure also becomes an instruction: `relogin` for a
worked. Since #3817 an invalid mint date is an explicit "expiry unknown:
invalid mint date" warning in owner status and logs, with the cause retained
in operational settings. It does not refuse boot or silently disable the
warning. Correcting the configured date restores estimation on the next
start; authentication itself is unchanged. Every auth failure also becomes an instruction: `relogin` for a
rejected token, `check_account` for an account the token cannot fix, and
`check_config` for a turn the backend refused before sending it. A keyless
test rehearses the rotation on a headless host.
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/codex-subscription-auth.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ flow and expose its own connection state, even if the user chooses the same
ChatGPT account. Native client credentials remain private to their owners;
responses, logs and documentation must not expose tokens or account identifiers.
Pi's existing Accounts flow remains the entry point for pi only
(`createPiAuthRoutes`, `packages/ui-server/src/routes/pi-auth.ts:60-61`;
(`createPiAuthRoutes`, `packages/ui-server/src/routes/pi-auth.ts:66-67`;
`PiAccountsSection`, `packages/ui-react/src/components/settings/pi-accounts.tsx:19-24`).

This is a go for implementing a separate Codex login in that Settings area,
Expand Down
8 changes: 4 additions & 4 deletions docs/decisions/http-api-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction.

The source audit on 2026-09-30 used
`e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth
(`createHealthRoutes`, `packages/ui-server/src/app.ts:998`), the API guard follows
public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1019`), and the
WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1234`).
(`createHealthRoutes`, `packages/ui-server/src/app.ts:1019`), the API guard follows
public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1040`), and the
WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1260`).
Static serving is conditional (`if (options.staticRoot)`,
`packages/ui-server/src/app.ts:1254-1275`). That order establishes access;
`packages/ui-server/src/app.ts:1280-1301`). That order establishes access;
it does not select compatibility status.

A hermetic real-app launch, with temporary brain root, in-memory database,
Expand Down
43 changes: 43 additions & 0 deletions docs/decisions/proportionate-containment.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,3 +109,46 @@ A PR that adds or changes a fail-closed guard answers these in its body:
(#3810).
- **Restart the server on latch.** Rejected: a durable latch survives restart
by design, and a process-lifetime one hides the cause.

## The two historical boot gates traced in #3817

The acceptance criteria permit retaining a boot refusal where tracing shows
that the current host cannot enforce the proposed restricted mode. These two
refusals remain; they are not covered by secondary-backend degraded health.

**Failed protected-file quarantine.** The result is a protected executable
input still in the brain, not merely a missing history record. The host
reconciles before it prepares the boundary or invokes the brain's CLI;
`reconcileExisting` refuses before installing its writer gate
(`reconcileExisting()`, `packages/ui-server/src/brain/host-execution.ts:100-113`).
The CLI version probe itself evaluates the brain's execution environment.
A read-only UI that continued this normal startup would already have crossed
the forbidden evaluation boundary before serving diagnostics. Neither a
strict turn profile nor a writer lock makes that configuration trusted.
Therefore the full app still refuses when quarantine cannot move the input.
The manifest retains the failed paths and error text with an open end record;
reconciliation retries the move on the next start
(`const close`, `packages/ui-server/src/brain/governed-manifest.ts:258-267`).
Repairing the quarantine destination preserves the bytes and permits that
retry; removing a protected input requires the owner's judgment. A separate
boot path that never evaluates the brain would be needed to serve recovery
while this guard is active; removing the assertion alone is unsafe.

**Interrupted operational restore.** This is an incomplete replacement of the
whole operational database and staging tree, including principals, schedules,
retained dialogue authority and budget reservations. It is not a single inbox
item. Resume accepts only the original snapshot checksum and root and an
unchanged logical database
(`restoreInboxSnapshot`, `packages/ui-server/src/inbox/snapshot.ts:428-445`).
Even ordinary authentication writes would make that target fail the equality
check. The final transaction settles reservations conservatively, pauses
schedules and invalidates old dialogue authority before marking it ready
(`const recovered`, `packages/ui-server/src/inbox/snapshot.ts:463-480`).
Starting the regular authenticated app over the pending database cannot
preserve this recovery contract, so its refusal remains. The existing local
`brain-ui-inbox restore --db <database> --brain-root <brain> --file <snapshot>
--json` operation resumes the same snapshot without starting the app. Choosing
the snapshot is an owner action; the snapshot bytes are not retained by the
pending row, so startup cannot reconstruct them automatically. Serving a
recovery UI here would require authentication independent of the database
being restored, rather than treating its historical principals as current.
2 changes: 1 addition & 1 deletion docs/decisions/runtime-requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -278,7 +278,7 @@ reciprocal host-version negotiation is involved.
| `probeBrainCliVersion` / `brainCliCommand` (`export async function probeBrainCliVersion`, `packages/ui-server/src/brain/client.ts:181-248`) | Reuse executable selection, wrapper, deadline and cleanup; add host floor composition, strict comparison and invocation verification without duplicating the 0.33.0 constant. |
| `installedAgentSdkVersion` (`export function installedAgentSdkVersion`, `packages/ui-backend-claude/src/runtime-probe.ts:55-61`) | Retain importer-relative resolution; validate package name/version and the owner's manifest range. |
| `selectedSpawn` / `probeClaudeRuntime` (`export function selectedSpawn`, `packages/ui-backend-claude/src/runtime-probe.ts:69-96`; `export async function probeClaudeRuntime`, `packages/ui-backend-claude/src/runtime-probe.ts:127-147`) | Keep SDK-selected command capture, native/JS override argv, environment, timeout and group cleanup; add strict identity validation and composed runtime floors. |
| `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:394-444`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. |
| `probeBackendRuntimes` (`export async function probeBackendRuntimes`, `packages/ui-server/src/agent/backend.ts:412-462`) | Forward validated host requirements; retain active-backend selection and separate unmeasured-pair logging. |
| `BackendModuleContext` / `BackendRuntimeReport` (`export interface BackendModuleContext`, `packages/ui-sdk/src/server/backend-module.ts:96-111`; `export interface BackendRuntimeReport`, `packages/ui-sdk/src/server/backend-module.ts:118-131`) | Extend the existing construction context for optional minimums. Keep report identities and `measured` meanings; a compatibility result must never occupy `measured.matches`. |
| `MEASURED_RUNTIME`, its guard and `scripts/measure-claude-runtime.ts` | Keep the constant, exact pair guard, keyless behavior probe and dated measurement receipts. A permitted pair can still be unmeasured. |
| Turn `reportRuntime` / `init` (`export function reportTurnRuntime`, `packages/ui-backend-claude/src/turn-reporting.ts:31-70`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-stream.ts:97-102`; `function initMatchesProbe`, `packages/ui-backend-claude/src/turn-stream.ts:184-196`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. |
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/scheduled-tasks.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`:
(`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`).
The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`).
- Production app wiring supplies recovery and budgets, without a dispatcher
(`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:542-558`).
(`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:557-573`).
A scripted nonempty ready-item test still reports no claim, attempt or
Activity root. That proves disabled wiring, not safe execution of a schedule.
- Headless plumbing checks backend support, a usable principal, lifetime and
Expand Down
6 changes: 3 additions & 3 deletions docs/decisions/session-principals.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source.
| Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` |
| Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** |
| Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` |
| Auth routes | `authRoutes`, `app.ts:1004` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1019`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) |
| Passkey management | `passkeyManagementRoutes`, `app.ts:1029` | mounted **after** the guard ("Mount AFTER the auth guard") |
| WS guard | `"/ws"`, `app.ts:1234-1251` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade |
| Auth routes | `authRoutes`, `app.ts:1025` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1040`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) |
| Passkey management | `passkeyManagementRoutes`, `app.ts:1049` | mounted **after** the guard ("Mount AFTER the auth guard") |
| WS guard | `"/ws"`, `app.ts:1260-1277` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade |
| WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context |
| WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown |
| Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor |
Expand Down
4 changes: 3 additions & 1 deletion docs/hosting/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -345,7 +345,9 @@ What the server does between logins:
- **Before expiry.** From 30 days before `expiresAt`, and after it, the server
logs a WARN at boot and at most once a day, naming the date and this
procedure. Without `BRAIN_UI_CLAUDE_TOKEN_MINTED_AT` it cannot tell, and says
so once at boot. A date it cannot read refuses the boot.
so once at boot. An invalid date keeps serving and reports "expiry unknown:
invalid mint date" in authenticated status and the boot log; correct the date
and restart to restore the estimate.
- **Proof it works.** `lastProvenAt` is the latest successful turn that ran on
the subscription (kept in the database, so it survives a restart and the
activity retention window), or a successful model-discovery call with the
Expand Down
23 changes: 20 additions & 3 deletions docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -348,13 +348,16 @@ universal Cache-Control header is promised.
the app's SQLite schema. Healthy: 200
`{ status: "healthy", uptime: number, timestamp: string }`, where uptime is
milliseconds since the route module initialized and timestamp is ISO UTC.
A failed secondary backend returns 200 with `status: "degraded"` and
`reasons: ["backend_unavailable"]`, retaining uptime and timestamp. Error text
and backend identities remain behind authentication on `/api/status`.
An unreadable database yields 503 `{ status: "unhealthy" }`, without detail.
It never exposes release, source commit, runtime, credentials or session state;
healthy does not certify upstream model or brain CLI availability.

**GET /api/status** is protected, accepts no inputs, and returns
`{ healthy: true, uptime, version, software, cronJobs, activeSession, metrics,
runtime?, subscription? }`. `version` is the configured source commit (default
`{ healthy: boolean, uptime, version, software, cronJobs, activeSession, metrics,
runtime?, subscription?, backendAvailability? }`. `version` is the configured source commit (default
`"dev"`), not a release; `software` is `{ release, sourceCommit }`. `cronJobs`
contains `{ name, lastRunAt, lastStatus, lastDurationMs, lastError }`, nullable
when a job has not run; it includes recorded jobs and configured in-process
Expand All @@ -364,6 +367,15 @@ series have name, kind (counter/updowncounter/histogram/gauge), numeric
value and scalar attributes; histogram value is the observation count.
Operational reads can fail with the common 500.

`backendAvailability` contains `unavailable` (this boot's excluded backends) and
`lastFailures` (the latest persisted failure per backend, retained after repair).
Each record has `backendId`, `phase: "resolution" | "runtime"`, `errorClass`,
`message`, `site` (the failed boot check) and ISO `at`. `healthy` is false while `unavailable` is nonempty.
The default backend must pass boot validation; unavailable secondary backends
are never constructed or routed to. Correct the package/runtime or host
configuration and start again to revalidate. Prior records alone do not imply
current degradation.

`runtime.workerHost` is whether this host can run agent workers (#1632):
`{ ordinary?, restricted? }`, each `{ available, checkedAt, trigger }` plus
`requirement` when unavailable. `checkedAt` is ISO UTC; `trigger` is `"boot"`,
Expand Down Expand Up @@ -400,7 +412,12 @@ and the [sync reporting contract](integration-contract/wire.md#activity-stream-r
`subscription` contains `tokenSet`, nullable ISO `mintedAt`, `expiresAt`,
`lastProvenAt`, `provenBy: "turn" | "model_discovery" | null` and nullable
`lastAuthFailure` (`errorClass`, ISO `at`, `action`, `source`, optional
`runId`, `message`, `status`). It never returns the token. Optional monitoring
`runId`, `message`, `status`). An invalid configured mint date leaves
`mintedAt` and `expiresAt` null and adds `expiryWarning` with
`reason: "invalid_mint_date"`, `message` starting "expiry unknown: invalid mint date",
`errorClass` and ISO `at`. It warns at boot and retains the last cause in the
operational settings store; it never refuses serving or changes authentication.
It never returns the token. Optional monitoring
fields reflect injected capabilities; they are not a liveness requirement.

## Login, passkeys and delegated credentials
Expand Down
4 changes: 4 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -1143,6 +1143,10 @@ Original fragment identities remain available at this entry point.

- [ui-server HTTP routes](integration-contract/http.md#ui-server-http-routes) (original line 1943).

<a id="degraded-backend-availability-and-unknown-expiry-additive-3817"></a>

- [Degraded backend availability and unknown expiry (additive, #3817)](integration-contract/http.md#degraded-backend-availability-and-unknown-expiry-additive-3817).

<a id="published-react-health-and-sync-helpers-breaking-health-correction"></a>

- [Published React health and sync helpers (breaking health correction)](integration-contract/http.md#published-react-health-and-sync-helpers-breaking-health-correction) (original line 1964).
Expand Down
Loading
Loading