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
8 changes: 8 additions & 0 deletions .changeset/native-history-removal.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@schlessera/brain-ui-sdk": minor
"@schlessera/brain-backend-claude": minor
"@schlessera/brain-backend-pi": minor
"@schlessera/brain-ui-server": patch
---

Backends can remove one explicitly retired chat's local native history (#3229). `BackendCapabilities.historyRemoval` and the optional `AgentBackend.removeSessionHistory()` are new; the Claude and Pi backends implement them. A removal first fences the session permanently, so it is no longer listed, read, resumed, archived or restored, even after a restart. It then waits for the session's running turns and readers, and removes the live, archived, staged and conflict copies, subordinate and branch files, display and prompt metadata and file observations. Links, hard links, redirected storage and replaced files are left untouched and reported as `partial`, never as removed. Nothing exposes deletion to users yet: the endpoint and interface are separate work, and provider-held copies and backups are outside local removal.
28 changes: 28 additions & 0 deletions api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1045,12 +1045,15 @@ export "./internal" (./src/internal.ts)
type QuestionObservation
REFERENCE_POOL_CHECKPOINT_BYTES
RTK_WORKER_ENV
type RemovalRun
type ReplayReceipt
type Reservation
type RestrictedEnvelope
STALE_NATIVE_WRITE
SUBPROCESS_ENV
type SessionPromptFacts
type SessionRetirement
type SessionRetirementOptions
type StateLedger
TURN_TEMP_BUDGET_ENV
TURN_TEMP_BYTES_ENV
Expand Down Expand Up @@ -1128,9 +1131,11 @@ export "./internal" (./src/internal.ts)
classifyOutwardCall
claudeMaskFilename
claudeReportedMaskPath
combineRemovalOutcomes
compileWorkerCommandPolicy
createLimitTracker
createNativeBrainManagerClient
createSessionRetirement
createStateLedger
createTurnTempPressure
createTurnTempPromoter
Expand Down Expand Up @@ -1164,11 +1169,13 @@ export "./internal" (./src/internal.ts)
mib
mountPointsUnder
nativeFileVersion
nativeObservationIdentity
nativeWorkerStartupInput
observeClassification
observeOutwardPlan
outputStagingLimit
outwardTarget
ownedNames
parseCliProviderOrigins
parseNativeBrainDelta
parseWorkerStateBytes
Expand Down Expand Up @@ -1198,6 +1205,8 @@ export "./internal" (./src/internal.ts)
recoveredWorkerFile
recoveredWorkerFiles
relayedProviderKeys
removeMetadataFile
removeOwnedArtifact
requestPolicyPermission
requireWorkerHost
requireWorkerHostAsync
Expand All @@ -1213,7 +1222,9 @@ export "./internal" (./src/internal.ts)
runMaintenanceWorker
runMaintenanceWorkerSync
sessionPromptContext
sessionPromptContextLocation
sessionReplay
sessionReplayLocation
startEgressProxy
startInferenceRelay
startProviderRelay
Expand Down Expand Up @@ -2313,6 +2324,9 @@ export "./server" (./src/server/index.ts)
type ServerUsage
type SessionDraftLimits
type SessionHistoryMessage
type SessionHistoryRemovalOutcome
type SessionHistoryRemovalRequest
type SessionHistoryRemovalResult
type SessionRecovery
type SessionRecoveryLatest
type SessionRecoveryPending
Expand Down Expand Up @@ -3474,6 +3488,7 @@ signatures (every public export and the types it is made of)
}[];
listSessions(): Promise<ChatSession[]>;
getHistory(sessionId: string): Promise<SessionHistoryMessage[]>;
removeSessionHistory?(req: SessionHistoryRemovalRequest): Promise<SessionHistoryRemovalResult>;
}
AgentPolicyRead (packages/ui-sdk/src/protocol.ts)
export interface AgentPolicyRead {
Expand Down Expand Up @@ -5230,6 +5245,7 @@ signatures (every public export and the types it is made of)
costReporting: boolean;
concurrentSessions: boolean;
followUp: boolean;
historyRemoval?: boolean;
}
BackendContractHarness (packages/ui-sdk/src/testing/index.ts)
export interface BackendContractHarness {
Expand Down Expand Up @@ -9926,6 +9942,18 @@ signatures (every public export and the types it is made of)
turnId?: string;
journal?: import("./turn-journal.js").TurnJournalSummary;
}
SessionHistoryRemovalOutcome (packages/ui-sdk/src/server/backend.ts)
export type SessionHistoryRemovalOutcome = "removed" | "partial" | "unknown";
SessionHistoryRemovalRequest (packages/ui-sdk/src/server/backend.ts)
export interface SessionHistoryRemovalRequest {
operationId: string;
sessionId: string;
signal?: AbortSignal;
}
SessionHistoryRemovalResult (packages/ui-sdk/src/server/backend.ts)
export interface SessionHistoryRemovalResult {
outcome: SessionHistoryRemovalOutcome;
}
SessionRecovery (packages/ui-sdk/src/protocol.ts)
export interface SessionRecovery {
sessionId: string;
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/async-collaboration.md
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ requires one enforcement mechanism with different named memberships for voice
and unattended work. Keep that requirement when implementing availability
control. Existing mandatory backend conformance supports safe rejection of an
unsupported restricted request; silently ignoring it is forbidden. The current
optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:602`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:626`). These are permission primitives,
optional inputs are (`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:608`) and (`noGrantSurface?: boolean`, `packages/ui-sdk/src/server/backend.ts:632`). These are permission primitives,
not a claim of filesystem or network containment.

The ordinary Claude assembly loads project settings and appends bridge tools
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/claude-code-runtime.md
Original file line number Diff line number Diff line change
Expand Up @@ -1311,7 +1311,7 @@ profile's `baseUrl` from `BRAIN_UI_CLAUDE_PROFILES`, else the server's
`ANTHROPIC_BASE_URL`, else first-party inference. The relay forwards to that
route, keeping its base path. Before the prompt is sent, the runner refuses a
route whose origin is neither first-party nor listed
(`const selectedUpstream`, `packages/ui-backend-claude/src/turn-runner.ts:430-445`).
(`const selectedUpstream`, `packages/ui-backend-claude/src/turn-runner.ts:441-456`).
Each dispatch checks the same list again before the credential is read. Native
settings may repeat the server's route, compared as a canonical origin and base
path, but never replace it. A discovered profile never carries a route or a
Expand Down
6 changes: 3 additions & 3 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1360,10 +1360,10 @@ also preserves the previous observation: it supplied no new bytes

Claude keeps these observations in its backend-owned session map
(`const fileVersionsBySession`,
`packages/ui-backend-claude/src/turn-runner.ts:105`). Pi keeps them in its
`packages/ui-backend-claude/src/turn-runner.ts:110`). Pi keeps them in its
backend-owned session runtime across fresh per-turn workers
(`const nativeFileVersions`,
`packages/ui-backend-pi/src/session-runtime.ts:19`); internal RPC reports
`packages/ui-backend-pi/src/session-runtime.ts:21`); internal RPC reports
observation phases for the actual granted native operation, not a supplied hash
or authority. Both also retain observations in host-private records and restore them before
resumed native tools run. Claude keeps these records beside its transcript
Expand All @@ -1373,7 +1373,7 @@ the canonical brain root and native session identity; filenames contain only a
SHA-256 identity. Atomic replacement, file and directory fsync, private modes,
regular-file validation and a 16 MiB per-session metadata bound protect the
record (`saveNativeObservations`,
`packages/ui-sdk/src/server/native-observation-storage.ts:66-79`).
`packages/ui-sdk/src/server/native-observation-storage.ts:70-83`).
Saves wait on the file system off the hosted server's event loop, land in call
order, and complete before the tool they guard proceeds (#2416).

Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/hardening.md
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ instead, and treat 8 as the question it was answering.
releases.** Dispatcher, store and page splits (U33) ship in the 0.34.x
train, never in the container release. Because U28 changes frame
production (`adapter.adapt(msg)`,
`packages/ui-backend-claude/src/turn-runner.ts:690`) and U33 changes frame
`packages/ui-backend-claude/src/turn-runner.ts:703`) and U33 changes frame
consumption
(`handleServerMessage`, `packages/ui-react/src/connection.ts:336`), the
same symptom could come from either, so they are **0.34.0** (seam) and **0.34.1** (splits), each its own
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/live-conversation.md
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ tool admission and execution, permissions, cancellation, terminal state and
resynchronization. Engine task requests are advisory until mapped to committed
user input. No native search, code-execution or alternate permission loop is
enabled. Both adapters can delegate through the existing `AgentBackend`
(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:708-751`);
(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:750-804`);
the host serializes work in a session and uses capability-checked follow-ups.

The [voice-permission decision](voice-permission.md) binds this interface.
Expand Down
6 changes: 3 additions & 3 deletions docs/decisions/policy-write-boundary.md
Original file line number Diff line number Diff line change
Expand Up @@ -640,7 +640,7 @@ result is held until the worker has exited and its state has been copied out,
and the state is checked again then. A `statfs` of the tmpfs with no whole page
free at either point, or a write error the worker reported, names the turn
`worker_state_exceeded` (`const unsaved`,
`packages/ui-backend-claude/src/turn-runner.ts:301-308`). A result, success or
`packages/ui-backend-claude/src/turn-runner.ts:312-319`). A result, success or
error, becomes an error result with that class and keeps its usage, so the
client never presents unsaved output as saved; what was written before the
limit is persisted with the usual checks, and if that copy-out is refused the
Expand All @@ -651,9 +651,9 @@ the worker prints after it, and a refusal is recognized by its class from any
copy of the module. A host cancellation outranks it. Cancellation is checked
again after worker settlement, so a buffered SDK success or error cannot
replace an accepted cancellation while exit or copy-out is pending
(`releaseTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:312-330`).
(`releaseTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:323-341`).
Generated terminals also await worker settlement before emission
(`emitTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:374-414`).
(`emitTerminal`, `packages/ui-backend-claude/src/turn-runner.ts:385-425`).
**Residual:** a turn that fills the tmpfs and frees space again between those
two checks is named only if the runtime printed the write error.

Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/runtime-requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ reciprocal host-version negotiation is involved.
| `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. |
| `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` (`const reportRuntime`, `packages/ui-backend-claude/src/turn-runner.ts:216-223`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-runner.ts:674-689`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. |
| Turn `reportRuntime` / `init` (`const reportRuntime`, `packages/ui-backend-claude/src/turn-runner.ts:227-234`; `if (msg.type === "system"`, `packages/ui-backend-claude/src/turn-runner.ts:687-702`) | Preserve actual per-turn SDK/runtime observations, billing/permission guards and normal failure terminal behavior. |
| Index schema and graph floors | Remain reader-specific integer schema checks; do not compare them as SemVer or turn `brain.db` into authoritative state. |

No new compatibility HTTP status field is required for enforcement. Keep
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/voice-permission.md
Original file line number Diff line number Diff line change
Expand Up @@ -620,7 +620,7 @@ matters because a reader cannot otherwise tell a live hazard from a fixed one.

**Closed, by #141 (`42a4d86`), which closed #124.** A turn now declares
`StartTurnRequest.enforceAllowedTools`
(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:602`)
(`enforceAllowedTools?: boolean`, `packages/ui-sdk/src/server/backend.ts:608`)
— the declaration this record asked for, by that name — and under it:

- The input-rewrite hooks no longer grant. `createAgentHook` and `createRtkHook`
Expand Down
12 changes: 12 additions & 0 deletions docs/integration-contract.md
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,18 @@ same-commit update of the index or relevant authoritative component. How they ar

The reasoning is in [decisions/contract-versioning.md](decisions/contract-versioning.md).

## Native history removal (additive, #3229)

`BackendCapabilities.historyRemoval?` and the optional
`AgentBackend.removeSessionHistory?()` let a host remove one explicitly retired
chat's locally owned native history, with content-free `removed`, `partial`
and `unknown` outcomes. A backend that does not advertise and implement both is
unsupported, and deletion refuses before retirement. The first-party Claude and
Pi backends implement it. No wire frame, HTTP route, CLI `--json` shape or MCP
tool changes; the deletion endpoint is not part of this change. See
[the package component](integration-contract/package-api.md#native-history-removal-additive-3229).
This ships in a minor; no breaking ruling is required.

## Agent runner unavailable in maintenance workers (additive, 0.45.0, #3243)

A credential-free maintenance worker's launcher sets
Expand Down
37 changes: 37 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,43 @@ passes its origin to `startInferenceRelay` as the new internal
origin, and a turn without a relay refuses to start. The first-party
Claude and pi backends implement all three.

## Native history removal (additive, #3229)

`BackendCapabilities` adds optional `historyRemoval?: boolean`, and
`AgentBackend` adds optional `removeSessionHistory?(req:
SessionHistoryRemovalRequest): Promise<SessionHistoryRemovalResult>`, exported
from `@schlessera/brain-ui-sdk/server` with
`SessionHistoryRemovalRequest` (`{ operationId: string; sessionId: string;
signal?: AbortSignal }`), `SessionHistoryRemovalResult` (`{ outcome }`) and
`SessionHistoryRemovalOutcome` (`"removed" | "partial" | "unknown"`).
Removal is supported only when the capability is `true` and the method exists;
the conformance suite in `@schlessera/brain-ui-sdk/testing` checks that they
agree. A host refuses deletion of a chat on any other backend before it
retires anything; older backends remain valid and simply do not support it.

A host calls it only for a chat its owner explicitly retired, under that
retirement's operation identity, as the
[deletion policy](../decisions/chat-history-deletion.md) allows. Before its first
await the backend fences the session durably and permanently: `listSessions`
omits it, `getHistory` returns `[]`, and resume, follow-up, archive and
restore refuse it, after a restart too. It then waits for the session's running
turns and readers to drain and removes every native artifact it owns: live,
archived, staged and conflict copies, subordinate and branch files, display and
prompt metadata and file observations. Only names derived from the validated
session identity are touched; a link, hard-linked file, redirected root or
artifact whose own header names another session is left in place.

The outcome is content-free and maps onto the host's per-store ledger:
`removed` only when every owned artifact is confirmed absent and the installed
runtime no longer lists the session; `partial` while owned content may remain,
including when `signal` aborts the caller's wait first (the removal keeps its
single owner and finishes after a genuine drain); `unknown` when an unexpected
failure left the state unconfirmed. Every outcome but `removed` is retried under
the same operation. A second operation for the same session, an invalid
identity or a redirected tombstone root rejects with `BackendRequestError`.
Previously sent provider bytes are never rewritten, and provider-held copies
are outside it. The first-party Claude and Pi backends implement it.

## Inbox provenance (additive, #2741)

The intake `createInboxIntake` returns adds `person(input, key, principal)`:
Expand Down
4 changes: 2 additions & 2 deletions docs/investigations/live-conversation-investigation.md
Original file line number Diff line number Diff line change
Expand Up @@ -254,7 +254,7 @@ requestId)`; actual tool requests additionally use their existing `toolUseId`.
Only committed original input supplies `StartTurnRequest.prompt`. The host
selects the pinned existing backend/profile, cancellation signal and
`BackendBridge`, and enforces the voice posture on new voice turns
(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:513-610`).
(`export interface StartTurnRequest`, `packages/ui-sdk/src/server/backend.ts:519-616`).
Do not feed approximate fragments or native task descriptions directly into
execution. Keep raw outputs/private memory in the host and return only reviewed
bounded facts needed by the voice service.
Expand All @@ -263,7 +263,7 @@ Backend reuse is structurally feasible for **both** adapters. `startTurn` is
already asynchronous and accepts a host AbortSignal. A busy same-session turn
is queued; new committed details use `followUp` only when the backend advertises
it, otherwise remain queued/reviewable
(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:708-751`).
(`export interface AgentBackend`, `packages/ui-sdk/src/server/backend.ts:750-804`).
Continued voice interaction never requires unsafe concurrent `startTurn`s.
This is source evidence and design mapping, not a real provider/backend trial.

Expand Down
2 changes: 1 addition & 1 deletion docs/plans/async-collaboration-requirements.md
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ Stated before the requirements because five of them derive from it.
- R24. **Headless execution needs a new request shape.** `StartTurnRequest` is
additive: `StartTurnRequest.autonomous` carries explicit persistence, origin, tool policy
and prompt configuration alongside the required permission postures
(`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:513-603`); ordinary Claude turns create an SDK session, emit
(`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:519-609`); ordinary Claude turns create an SDK session, emit
`session_info`, and persists history by default. The installed SDK supports
`persistSession: false`; pi provides `SessionManager.inMemory`. Drive this mode
with a synthetic checkpoint bridge and server-selected authority; the
Expand Down
2 changes: 1 addition & 1 deletion docs/plans/async-collaboration.md
Original file line number Diff line number Diff line change
Expand Up @@ -1189,7 +1189,7 @@ and a server-selected tool policy.
**Files:**
- Modify: `packages/ui-sdk/src/server/backend.ts` (the additive `StartTurnRequest.autonomous` mode carries persistence,
origin, tool policy and prompt configuration —
(`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:513-603`))
(`export interface StartTurnRequest {`, `packages/ui-sdk/src/server/backend.ts:519-609`))
- Modify: `packages/ui-backend-claude/src/backend.ts` (`persistSession: false`, synthetic
bridge)
- Modify: `packages/ui-server/src/activity/recorder.ts` (server-selected
Expand Down
Loading
Loading