Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
50cc418
fix(ui-server): settle session binding before relay admission
schlessera Nov 8, 2026
2ac5d46
Merge remote-tracking branch 'origin/main' into fix/3725-relay-sessio…
schlessera Nov 8, 2026
d8709a2
docs: align relay safety ordering and source citations
schlessera Nov 8, 2026
e571375
chore: reconcile relay binding fix with current main
schlessera Nov 9, 2026
ebc6600
chore: refresh relay binding fix and native diagnostics
schlessera Nov 9, 2026
b3b8f79
chore: refresh relay fix over transcript contrast
schlessera Nov 9, 2026
e5a59c1
test(ui-server): refresh relay binding proof and turn isolation
schlessera Nov 10, 2026
0c519c9
chore: refresh relay binding proof over host recovery changes
schlessera Nov 10, 2026
3b23172
chore: align relay candidate with hybrid CI proof policy
schlessera Nov 10, 2026
6057be2
test(ui): give provider-history hosts live principal authority
schlessera Nov 10, 2026
a1062a5
chore: refresh relay binding candidate over current main
schlessera Nov 10, 2026
c0e78f3
chore: refresh relay binding against voice and recovery updates
schlessera Nov 10, 2026
f1731f1
chore: compose relay binding with recorded history boundaries
schlessera Nov 10, 2026
2f30519
chore: refresh candidate metadata after documentation-only base advance
schlessera Nov 10, 2026
e17119e
Merge main recorder containment and align relay loss controls
schlessera Nov 11, 2026
0a86fa7
Merge commit '5064308eec6c767a8208d5a19d425baad5ef8445' into fix/3725…
schlessera Nov 11, 2026
891d26b
Merge commit 'e3bf372c2b402f6905e93b17c85ee6ddfb1e738c' into fix/3725…
schlessera Nov 11, 2026
2f705f0
Merge commit '067d1904bafccf0503a1e3effd6bd260ebf34769' into fix/3725…
schlessera Nov 11, 2026
a0bec40
Merge commit '2b547ef00b85a314f7478c9f3c2aeb3d5ab0dc2e' into fix/3725…
schlessera Nov 11, 2026
397a602
Merge commit '4a8c43f383ffd9806e5bedd1e4e00d2400f03149' into fix/3725…
schlessera Nov 11, 2026
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/relay-session-binding.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": patch
---

Wait for a turn's announced session binding before relay admission, avoiding a healthy inference refusal when its identity commits between safety checks. Keep final safety and authority fences, and refuse failed or cancelled binding settlement.
16 changes: 8 additions & 8 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -2257,7 +2257,7 @@ reports which applies as `governed.egress`. Making the relay work without
managed storage is follow-up work. Each connection is recorded as a governance event, and a recording
failure ends the turn. Without a governance recorder the policy still applies
and only the records are absent (`prepareTurnEgress`,
`packages/ui-server/src/brain/turn-egress.ts:83-203`). The note says egress is
`packages/ui-server/src/brain/turn-egress.ts:84-204`). The note says egress is
recorded only when the backend actually routed the worker through the proxy.
API-key Claude profiles (2026-10-22) and pi turns (2026-10-23) are routed
too. A pi turn whose credential the relay cannot carry is refused rather than
Expand Down Expand Up @@ -3859,7 +3859,7 @@ outward host skips the card only while every classified call in progress is a
visible read, or an approved outward action that names that host. A GitHub
write names the GitHub API hosts, and a push or HTTP write names its target's
host. Any unknown or opaque call in progress withholds the exception
(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:59-81`).
(`createOutwardCalls`, `packages/ui-server/src/brain/turn-egress.ts:60-82`).
A background process left by an earlier call can still connect inside such a
window; the proxy records it either way.

Expand All @@ -3873,7 +3873,7 @@ listen on other ports: `gmail.googleapis.com`, `graph.microsoft.com`,
`smtp.sendgrid.net`, `api.mailgun.net`, `api.eu.mailgun.net`,
`smtp.mailgun.org`, `smtp.eu.mailgun.org`, `api.postmarkapp.com`,
`smtp.postmarkapp.com`, `api.resend.com` and `smtp.resend.com`
(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:19-22`).
(`MAIL_SUBMISSION_PORTS`, `packages/ui-server/src/brain/turn-egress.ts:20-23`).
Microsoft Graph and Exchange Online carry more than mail, so their reads by
an opaque script also wait on the card. The coordinator chose this list for
#1665; the maintainer may override it.
Expand Down Expand Up @@ -3999,7 +3999,7 @@ charges only after admission); otherwise it is refused and recorded as an
`egress_denial` with reason `taint_allowlist` (an interactive turn asks first
since 2026-11-03, see [below](#tainted-destinations-ask)). The taint list
narrows and never widens: deny and `allowlist` mode still apply first (`prepareTurnEgress`,
`packages/ui-server/src/brain/turn-egress.ts:83-229`). Hosts without managed
`packages/ui-server/src/brain/turn-egress.ts:84-230`). Hosts without managed
native storage have no proxy, so the Bash classifier remains their shell rule
and nothing narrows their egress.

Expand Down Expand Up @@ -4047,12 +4047,12 @@ through the turn's tool-permission card (`toolName: "Network"`, `kind:
(`const narrowing`, `packages/ui-sdk/src/server/egress-proxy.ts:198-203`). The
card names the destination, the session's first taint source and the
consequence of allowing it
(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:38-43`).
(`taintedDestinationDescription`, `packages/ui-server/src/brain/turn-egress.ts:39-44`).
Concurrent connections to the same host share one card. An allowed
connection's admission adds its host to the turn's contacted hosts, and its
charged `egress_connection` record carries the host into the session's later
turns, so it is not asked for again; a different host still asks
(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:167-178`).
(`const approveTainted`, `packages/ui-server/src/brain/turn-egress.ts:168-179`).
A decline refuses: the record stays an `egress_denial` with reason
`taint_allowlist`, and the 403 carries a short reason the tool can print (`function describeRefusal`,
`packages/ui-sdk/src/server/egress-proxy.ts:88-104`). Stopping the turn while the
Expand All @@ -4076,7 +4076,7 @@ the byte ceiling, an unapproved outward host, or a tainted session's host
outside its allow-list, with the session's first taint source and what the
user can do (`function describeRefusal`,
`packages/ui-sdk/src/server/egress-proxy.ts:88-104`; the source wording,
`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:194`). The status
`cause: () =>`, `packages/ui-server/src/brain/turn-egress.ts:195`). The status
line carries the reason because `curl -v`, `git` and `egress-connect` print
only that line for a refused CONNECT. The provider relay passes the proxy's
reason through as the refusal body's `error.message` and an additive
Expand Down Expand Up @@ -4181,7 +4181,7 @@ admission (`relayed`, `packages/ui-sdk/src/server/egress-proxy.ts:338`), and
worker HTTP and `CONNECT` traffic cannot claim it, even to a provider's host
(`narrowed`, `packages/ui-sdk/src/server/egress-proxy.ts:196`). Turn egress
records neither a taint nor a contacted host for the operation
(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:154-157`). So in a
(`admitted`, `packages/ui-server/src/brain/turn-egress.ts:204-209`). So in a
tainted session, the worker's own traffic stays narrowed away from the
provider's host.

Expand Down
6 changes: 6 additions & 0 deletions docs/decisions/session-safety-reviews.md
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,12 @@ history adoption and local pending/loss changes advance admission even when the
global cursor does not. Pending-input overlays and capacity grouping use the
same retained aliases. The history/review cursor keeps its existing meaning.

A host relay joins its own announced session binding before taking a fresh
admission snapshot. The wait is bounded and abortable, and a drained catalog
queue alone does not prove that the binding committed. Failed or indeterminate
binding refuses. This ordering never exempts independent pending input or retries
a provider request; the final synchronous safety and authority fences still apply.

Only effective taint and the trust slice update live. Ordinary governance
budgets, profiles and commands keep turn-bound semantics. Trust removal fences
new active-turn dispatch before its enforcing receipt; ongoing input must split
Expand Down
8 changes: 5 additions & 3 deletions docs/plans/reviewable-session-safety.md
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,11 @@ public design or its fixtures. Fictional examples use the Odysseus world.
never prove finalized delivery or complete coverage.
- The turn proxy records each admitted non-provider connection and terminal
exposure observation (`prepareTurnEgress`,
`packages/ui-server/src/brain/turn-egress.ts:83-269`). Relay admissions join
this proxy's submitted terminal observations before reading fresh safety,
without excluding independent pending input. A raw CONNECT reveals
`packages/ui-server/src/brain/turn-egress.ts:84-272`). Relay admissions join
this proxy's submitted terminal observations and its own announced session
binding before reading fresh safety (`settleTurnSessionBinding`,
`packages/ui-server/src/ws/bridge-session-binding.ts:14-28`), without excluding
independent pending input. A raw CONNECT reveals
only an authority and opaque bytes, not a repository path or inner protocol
(`startEgressProxy`, `packages/ui-sdk/src/server/egress-proxy.ts:124-359`).
- Outward decisions read session taint at admission (`prepareOutwardPlan`,
Expand Down
17 changes: 17 additions & 0 deletions packages/ui-sdk/tests/fixtures/ordinary-identity-ws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,8 +41,20 @@ const backend = createClaudeBackend({ brainPath: brain, profiles: [{ id: "odysse
ANTHROPIC_API_KEY: "odysseus-fictional-api-key", HOME: home, CLAUDE_CONFIG_DIR: config, PATH: "/usr/local/bin:/usr/bin:/bin",
CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: "1", DISABLE_AUTOUPDATER: "1" }) }], log() {} });
const backendProfiles: Array<string | undefined> = [];
const admissionReads: Array<ReturnType<NonNullable<Parameters<typeof backend.startTurn>[0]["bridge"]["admissionSafety"]>["read"]>> = [];
const observedBackend = { ...backend, startTurn(request: Parameters<typeof backend.startTurn>[0]) {
backendProfiles.push(request.workerSandbox?.profile);
// Observe the real host gate synchronously, returning each original read
// unchanged. Native refusals otherwise collapse to a generic HTTP 403.
const safety = request.bridge.admissionSafety;
if (safety) {
const read = safety.read.bind(safety);
safety.read = () => {
const value = read();
if (admissionReads.length < 64) admissionReads.push({ ...value });
return value;
};
}
return backend.startTurn(request);
} };
const observability = createRecordingObservability(), secret = "odysseus-fixture-cookie-secret-0123456789";
Expand Down Expand Up @@ -160,6 +172,11 @@ try {
expect(backendProfiles, "ACTUAL_MANAGED_WS_BACKEND_SANDBOX").toEqual([profile]);
console.log(JSON.stringify({ profile, warm, admittedProfiles, backendProfiles, requests, terminal: frames.filter(frame => frame.type === "result" || frame.type === "error"),
limitations: observability.logs.records().filter(log => log.severity === "WARN" || String(log.body).includes("governed profile is unavailable")).map(log => log.body) }));
const terminalTurnId = frames.find(frame => frame.type === "result" || frame.type === "error")?.turnId;
console.log(JSON.stringify({ actualManagedAdmission: { profile, warm, reads: admissionReads,
egress: app.db.query(`SELECT json_extract(payload,'$.method') method, json_extract(payload,'$.host') host,
json_extract(payload,'$.outcome') outcome, json_extract(payload,'$.reason') reason
FROM governance_events WHERE turn_id=? AND kind='egress_connection' ORDER BY id DESC LIMIT 16`).all(String(terminalTurnId ?? "")) } }));
expect(requests, "ACTUAL_MANAGED_WS_NATIVE_REQUEST").toEqual([{ model: "claude-haiku-4-5", history: 1, apiCredential: true }]);
expect(frames.some(frame => frame.type === "result" && frame.outcome === "success"), "ACTUAL_MANAGED_WS_NATIVE_RESULT").toBe(true);
expect(frames.some(frame => frame.type === "error"), "ACTUAL_MANAGED_WS_ADMISSION_NO_ERROR").toBe(false);
Expand Down
13 changes: 8 additions & 5 deletions packages/ui-server/src/brain/turn-egress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type { GovernanceEventInput } from "../governance/events.js";
import { contactedHosts, recordFirstTaint, sessionTaint, type TaintSource } from "../governance/session-taint.js";
import type { GovernanceWrites } from "../governance/event-writes.js";
import { safetyProjection } from "../governance/safety-store.js";
import { settleTurnSessionBinding } from "../ws/bridge-session-binding.js";

type Classification = Extract<BackendActivityEvent, { kind: "outward_classification" }>["classification"];
const GITHUB_API_HOSTS = ["api.github.com", "uploads.github.com"] as const;
Expand Down Expand Up @@ -248,18 +249,20 @@ export async function prepareTurnEgress(options: {
const relayOperation = (kind: "inference" | "relayed", method: string, target: URL, signal: AbortSignal) => {
const operation = proxy[kind](method, target, signal);
return { ...operation, async admit() {
// A completed worker connection may still be committing its terminal
// exposure. Join only this turn proxy's submitted records before taking
// a fresh admission snapshot; independent pending input still refuses.
// Join this proxy's terminal records and this bridge's announced
// session binding before the new snapshot. A concurrent FULL binding
// must not change a healthy scope underneath its first admission.
// Independent pending input still refuses in the unchanged final fences.
if (operation.signal.aborted) return false;
let abort: (() => void) | undefined;
try {
const ready = await Promise.race([settled().then(() => true), new Promise<false>(resolve => {
const ready = await Promise.race([settled().then(() => settleTurnSessionBinding(original, operation.signal)).catch(() => false), new Promise<false>(resolve => {
abort = () => resolve(false);
operation.signal.addEventListener("abort", abort, { once: true });
if (operation.signal.aborted) resolve(false);
})]);
return ready && !operation.signal.aborted && await operation.admit();
if (!ready) { operation.finish("denied", "session_binding_unavailable"); return false; }
return !operation.signal.aborted && await operation.admit();
} finally { if (abort) operation.signal.removeEventListener("abort", abort); }
} };
};
Expand Down
28 changes: 28 additions & 0 deletions packages/ui-server/src/ws/bridge-session-binding.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/** The host bridge owns its announced identity's storage settlement. */
import type { BackendBridge } from "@schlessera/brain-ui-sdk/server";
import { waitWhile } from "../brain/authority-hold.js";
import { STORAGE_SETTLEMENT_MS } from "../db/settlement.js";
import type { BridgeContext } from "./bridge-capabilities/context.js";

const contexts = new WeakMap<BackendBridge, BridgeContext>();

export function retainTurnSessionBinding(bridge: BackendBridge, context: BridgeContext): void {
contexts.set(bridge, context);
}

/** Join only this bridge's announced binding, before minting admission authority. */
export async function settleTurnSessionBinding(bridge: BackendBridge, signal: AbortSignal): Promise<boolean> {
const ctx = contexts.get(bridge);
if (!ctx) return true;
const settled = await waitWhile(() => !!ctx.sessionBinding.pending && ctx.current(),
() => ctx.sessionBinding.pending!, signal, Date.now() + STORAGE_SETTLEMENT_MS);
if (!settled || signal.aborted || !ctx.current() || ctx.sessionBinding.pending || ctx.sessionBinding.failed) return false;
const db = ctx.host.activity?.governanceDb, sessionId = ctx.turn.sessionId;
// Catalog accounting reports failures without rejecting settled(). Check
// the actual collection binding too; a drained queue is not commit proof.
if (db && sessionId !== null) {
return !!db.query(`SELECT 1 FROM safety_collections c JOIN safety_sessions s ON s.session_id=c.session_id
WHERE c.turn_id=? AND c.session_id=?`).get(ctx.turnId, sessionId);
}
return true;
}
2 changes: 2 additions & 0 deletions packages/ui-server/src/ws/bridge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import { createScratch } from "./bridge-capabilities/scratch.js";
import { createAttachmentRead } from "./bridge-capabilities/attachments.js";
import { createWebAccess } from "./bridge-capabilities/web.js";
import { createEffectiveSafety } from "../governance/effective-safety.js";
import { retainTurnSessionBinding } from "./bridge-session-binding.js";

export { emitTurnError } from "./bridge-capabilities/turn-error.js";

Expand Down Expand Up @@ -90,6 +91,7 @@ export async function makeBridge(host: WsHost, turn: RunningTurn, options: MakeB
},
});
}
retainTurnSessionBinding(bridge, ctx);
return bridge;
}

Expand Down
13 changes: 13 additions & 0 deletions packages/ui-server/tests/fixtures/relay-binding-probe.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import type { Database } from "bun:sqlite";
export const url = import.meta.url;
export function setup(db: Database) {
return {
hold(gate: Int32Array, entered: Int32Array) {
db.transaction(() => {
Atomics.store(entered, 0, 1); Atomics.notify(entered, 0);
if (Atomics.wait(gate, 0, 0, 5000) === "timed-out") throw new Error("BINDING_PROBE_RELEASE_REQUIRED");
}).immediate();
},
committed(done: Int32Array) { Atomics.store(done, 0, 1); Atomics.notify(done, 0); },
};
}
Loading
Loading