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/3815-reconcile-uncertain-charges.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
"@schlessera/brain-ui-sdk": minor
"@schlessera/brain-backend-claude": patch
"@schlessera/brain-backend-pi": patch
"@schlessera/brain-ui-server": minor
---

Keep reconciling refused worker cleanup and unreadable compute jobs without a restart, retaining their reservations until confirmation. Retry superseded checkpoint cleanup without stopping active turns unless the retained-checkpoint bound blocks a safe observation. Record cleanup causes and recovery in Activity, and expose durable checkpoint cleanup diagnostics in authenticated status.
16 changes: 16 additions & 0 deletions api-report/ui-sdk.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1208,10 +1208,16 @@ export "./internal" (./src/internal.ts)
BRAIN_INTERACTION_GUIDANCE
BRAIN_SCRATCH_DIR
BRAIN_WORKSPACES_DIR
CLEANUP_RETRY_ATTEMPTS
CLEANUP_RETRY_BASE_MS
CLEANUP_RETRY_MAX_MS
CREDENTIAL_FREE_ENV
type ClassificationAnswers
type ClassificationPlan
type ClassificationRequest
type CleanupNotice
type CleanupReconciler
type CleanupReconcilerOptions
type CompiledWorkerCommandPolicy
DEFAULT_TURN_TEMP_BYTES
type EgressRecord
Expand Down Expand Up @@ -1268,6 +1274,7 @@ export "./internal" (./src/internal.ts)
RTK_WORKER_ENV
type RemovalRun
type Reservation
type RetainedCleanup
STALE_SAFETY_ADMISSION
SUBPROCESS_ENV
type SessionPromptFacts
Expand Down Expand Up @@ -1331,6 +1338,7 @@ export "./internal" (./src/internal.ts)
commitOutwardPlan
compileWorkerCommandPolicy
conversationOrientation
createCleanupReconciler
createLimitTracker
createNativeBrainManagerClient
createSessionRetirement
Expand Down Expand Up @@ -1389,6 +1397,7 @@ export "./internal" (./src/internal.ts)
probeNativeMaintenanceWorker
probeWorkerHost
probeWorkerHostAsync
processCleanupReconciler
processStateLedger
projectConversationGuidance
promptPrefixFingerprint
Expand Down Expand Up @@ -5887,6 +5896,13 @@ signatures (every public export and the types it is made of)
}>;
BackendActivityEvent (packages/ui-sdk/src/server/backend.ts)
export type BackendActivityEvent = {
kind: "worker_cleanup";
state: "retrying" | "resolved";
bytes: number;
turnTempBytes: number;
errorClass?: string;
message?: string;
} | {
kind: "prompt_prefix";
prefix: import("../protocol.js").PromptPrefixFingerprint;
resumed: boolean;
Expand Down
11 changes: 11 additions & 0 deletions api-report/ui-server.txt
Original file line number Diff line number Diff line change
Expand Up @@ -1573,6 +1573,12 @@ signatures (every public export and the types it is made of)
statCheckpoint?: ReturnType<typeof createNativeBrainManagerClient>["statCheckpoint"];
listCheckpoint?: ReturnType<typeof createNativeBrainManagerClient>["listCheckpoint"];
}
NativeJournalReleaseAccounting (packages/ui-server/src/brain/native-journal-observer.ts)
export interface NativeJournalReleaseAccounting {
pending: number;
failed: number;
retainedBytes: number;
}
NativeManagerReady (packages/ui-sdk/src/server/native-brain-manager-protocol.ts)
export interface NativeManagerReady {
brainPath: string;
Expand Down Expand Up @@ -2198,6 +2204,7 @@ signatures (every public export and the types it is made of)
referenceCheckpoints?: ReferenceWorktreeCheckpointLedger;
changed?: (turnId: string, sessionId: string, summary: TurnJournalSummary) => void;
idleObservationMs?: number;
log?: Logger;
}
VoiceConfig (packages/ui-server/src/config/env.ts)
export interface VoiceConfig {
Expand Down Expand Up @@ -2529,6 +2536,10 @@ signatures (every public export and the types it is made of)
inode: string;
note: string;
};
cleanupStatus(): {
lastFailure: unknown;
retained: import("./native-journal-observer.js").NativeJournalReleaseAccounting;
};
close(): Promise<void>;
configurationCoverage(): ConfigurationCoverageRead;
coverPaths(turnId: string, paths: readonly string[]): void;
Expand Down
8 changes: 5 additions & 3 deletions docs/decisions/external-compute.md
Original file line number Diff line number Diff line change
Expand Up @@ -638,7 +638,7 @@ maintainer ruled on four more questions on 2026-11-02.
- **Configuration as data.** The host reads `brain config check --json`'s new
`compute` summary in a credential-free strict worker that sees only the
policy's protected paths, once per turn, as it reads the taxonomy
(`readHostedComputeConfig`, `packages/ui-server/src/brain/compute-host.ts:977-989`). A
(`readHostedComputeConfig`, `packages/ui-server/src/brain/compute-host.ts:980-992`). A
provider value is reported by id only. A job keeps the instance
configuration it was admitted under, so its driver never reaches another
account however the brain changes later.
Expand Down Expand Up @@ -717,8 +717,10 @@ These refine the notes above; where they differ, these hold.
tracked, and is retried. A job the host abandons settles its reservation as
unknown, and at boot a reservation left without a job record settles as
unknown; both keep counting at the reserved amount, never zero. A job the
driver stops advancing after repeated failures keeps its reservation active
and its run flagged stuck until the next restart reattaches it.
driver cannot advance after repeated failures keeps its reservation active
and its run flagged stuck, with the cause in Activity. Under #3815 it keeps
visiting at the capped interval until settlement can be confirmed, without
requiring a restart or another admitted turn.
- **Activity over HTTP.** `GET /api/activity/runs` and
`GET /api/activity/runs/:runId` return `compute` runs only to a request that
declares the capability, as the live stream does.
Expand Down
50 changes: 24 additions & 26 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1469,7 +1469,7 @@ starts one per result and carries on
(`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:272`).
The wait is the observation's hold. `held` takes it synchronously, before it
queues the capture
(`function held<T>`, `packages/ui-server/src/brain/turn-journal.ts:240-261`),
(`function held<T>`, `packages/ui-server/src/brain/turn-journal.ts:246-267`),
and the scope monitor's hold freezes every active turn's productive workers
until the capture completes (`before() {`,
`packages/ui-server/src/brain/turn-scope.ts:158-166`). Pi's agent loop runs in
Expand All @@ -1481,7 +1481,7 @@ tracked the hold, not the bridge call.
proven read-only, no other call of an active turn is still running, and no
active turn has run a call whose effects may outlast it
(`toolEnded(turnId: string, toolUseId: string)`,
`packages/ui-server/src/brain/turn-journal.ts:550-557`). Admission, turn end,
`packages/ui-server/src/brain/turn-journal.ts:551-558`). Admission, turn end,
the 15-second timer, scope-limit observations, approved policy writes and
removal coverage observe exactly as before.

Expand Down Expand Up @@ -1606,7 +1606,7 @@ these versions as metadata-only and never open them for retention
kind, mode, size and its ignored flag, carries `metadataOnly: true` and records
its opaque change stamp, with no content hash and no symlink target. Two
versions of equal size are told apart by that stamp, as ignored ones are
(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:76`),
(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:81`),
so every observed refresh remains a recorded change. A metadata-only version is an intentional
observation state: it adds no `missing` entry and does not make the turn
partial. Removal coverage never treats the family as eligible, and history
Expand All @@ -1618,7 +1618,7 @@ stays now counts its largest size once too, rather than each version.
**History.** History presents every index-family version as metadata-only
however it was recorded, so a version an earlier release retained is no
longer read
(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:69-74`).
(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:74-79`).
The reader groups these entries as the search index, recorded by size and
timestamps only, with no review action. Preview reports `metadata_only` and
download has nothing to serve. History revert and Undo read that same
Expand Down Expand Up @@ -1853,15 +1853,15 @@ brain and every managed worktree, has its own owner, and each owner keeps at
most `NATIVE_RELEASE_BACKLOG`, two, previous checkpoints retained, whether
queued or failed. An observation makes room before it takes its own
checkpoint (`async function reserveRelease`,
`packages/ui-server/src/brain/native-journal-observer.ts:330-336`): it waits
`packages/ui-server/src/brain/native-journal-observer.ts:349-355`): it waits
inside the hold for the oldest queued release, or, when failed releases fill
the bound, retries the oldest one inside the hold, as every release ran
before. If that retry fails, the observation is refused before it takes a
checkpoint, so the bound is never exceeded. Each retained checkpoint is charged with an upper bound of the file content
it holds that the live root no longer has: the bytes of every file version
replaced or removed since it was taken
(`releases(): NativeJournalReleaseAccounting`,
`packages/ui-server/src/brain/native-journal-observer.ts:483-487`).
`packages/ui-server/src/brain/native-journal-observer.ts:505-509`).
Directory and other metadata extents are not counted. The store's free space,
which the `free_space_floor` scope limit reads, counts the actual extents until
each release completes. Shutdown waits for every queued release, retries
Expand All @@ -1870,17 +1870,15 @@ checkpoint still retained; startup recovery releases those. A release that
never settles is bounded by the manager client's transport deadline, not by
the owner.

**A failed release.** The checkpoint stays retained and charged until a
retry, and the journal treats the failure as the hold did
(`const releaseFailed`, `packages/ui-server/src/brain/turn-journal.ts:182-190`):
every active turn stops and its record is partial, a hold the failure
overlaps kills its held workers instead of resuming them, and an admission
requested before the failure, even one still queued behind other journal work,
is refused. A turn that finished before the failure keeps its record:
its terminal capture was recorded before the release began, and the failure
concerns storage cleanup, not what the journal holds. A failure inside the
hold, of a checkpoint, a delta, a capture, the retry of a failed release or the
release of an aborted observation, is unchanged.
**A failed release (revised by #3815).** The superseded checkpoint stays
retained and charged, and its owner retries every thirty seconds without a new
observation. Its replacement observation already committed, so the failure
neither stops active turns nor makes their records partial, and admissions
continue while the retained-checkpoint bound has room. The cause and checkpoint
identity are logged and recorded in the affected turns' authenticated Activity.
Only a full backlog that cannot make room refuses the next safe observation.
Failures taking a checkpoint, reading its delta, capturing its versions or
committing the observation retain their existing containment.

**Tests.** A fresh launch and the shared interpreter answer each refused
inspection with the same exit status, output and traceback; every request sees
Expand Down Expand Up @@ -3707,10 +3705,10 @@ end-of-turn cleanup that the awaited close above could not confirm.

- **The turn still fails.** The refusal is the turn's, as before; the
reconciler only takes ownership of the retryable close and the reservation.
- **Finite retries, then observable failure.** It retries the close with
capped exponential backoff and a finite number of attempts. A close still
refused after the last attempt is logged with the runtime-state and
turn-temp allowance it keeps charged until the server restarts.
- **Capped backoff without giving up (revised by #3815).** Both backends
retain a retry owner, including Pi initialization failures. After the
foreground retry count, the owner continues at the capped delay. Activity
records the cause, charged allowances and later confirmation.
- **Release once, only on confirmation.** The reservation is released exactly
once, after a retry resolves. An unconfirmed close never releases it.
- **Shutdown releases nothing and waits for nothing.** It cancels pending
Expand All @@ -3719,10 +3717,10 @@ end-of-turn cleanup that the awaited close above could not confirm.
never hold the process open.

The owner is the reconciler
(`export function createCleanupReconciler`, `packages/ui-backend-claude/src/cleanup-reconciler.ts:66-125`), and the turn
(`export function createCleanupReconciler`, `packages/ui-sdk/src/server/cleanup-reconciler.ts:75-148`), and the turn
hands its refusal over where it awaits the close
(`const close = async`, `packages/ui-backend-claude/src/worker-spawn.ts:273-284`). Pi and a launch
whose own cleanup is unconfirmed are outside this ruling.
(`const close = async`, `packages/ui-backend-claude/src/worker-spawn.ts:273-284`). Pi supervision now uses the same owner; launch failures before a handle is
returned remain the launcher's responsibility.

### Turn completion includes worker teardown — 2026-10-25

Expand Down Expand Up @@ -4321,7 +4319,7 @@ attribution. If an existing same-session/turn taint event precedes an agent
observation, the journal retains its source ID with that change. Replay never
infers taint from a later event, and absence of evidence does not assert complete
untrusted-input detection. User history operations are not tainted agent writes
(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:375-440`).
(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:380-445`).

Claude auto-memory persists outside the authoritative brain. Its validated
native copy-out wraps each changed direct `.md` note in host journal retention:
Expand All @@ -4344,7 +4342,7 @@ memory completion of the earlier 0.42.0 steering slice, not a widening of memory
providers or a claim of capturing intervening external writes. The copy-out
boundary is `const write`, `packages/ui-backend-claude/src/worker-state.ts:210-224`;
retention/finalization is `persistClaudeMemory`,
`packages/ui-server/src/brain/turn-journal.ts:647-677`; destination-bound recovery
`packages/ui-server/src/brain/turn-journal.ts:657-687`; destination-bound recovery
is `const target`, `packages/ui-server/src/brain/turn-revert.ts:113-123`.

### Concurrent edits
Expand Down
2 changes: 1 addition & 1 deletion docs/decisions/journal-database.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,7 +97,7 @@ that no pre-charge covers. The evidence is on the issue.
readers understand the arrays until then, and an empty legacy array stays
"no set recorded". The brain's current set is the one the most recent complete,
inventoried turn recorded
(`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:728-734`).
(`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:738-744`).
The sets table is an ordinary rowid table, as every journal table is: the
operational backup copies and compares journal rows in rowid order.

Expand Down
4 changes: 2 additions & 2 deletions docs/decisions/managed-worktrees.md
Original file line number Diff line number Diff line change
Expand Up @@ -125,8 +125,8 @@ A managed worktree is not inside the brain, so the brain's checkpoints never
cover it. The turn journal observes each covered worktree as its own root,
through that worktree's read-only checkpoints and deltas and the same observer
and capture as the brain
(`attachWorktree(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:562-574`;
`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:392-406`).
(`attachWorktree(turnId: string`, `packages/ui-server/src/brain/turn-journal.ts:563-575`;
`// Each managed worktree is observed through its own checkpoints`, `packages/ui-server/src/brain/turn-journal.ts:397-411`).
Coverage starts with a baseline checkpoint and inventory before the grant, and
every journal observation, periodic, at a scope cap or at the turn's end, then
observes the worktree too.
Expand Down
3 changes: 1 addition & 2 deletions docs/decisions/proportionate-containment.md
Original file line number Diff line number Diff line change
Expand Up @@ -55,8 +55,7 @@ design, not an afterthought.
- Proportionate: an uncertain worker cleanup stays charged and is retried
until a close is confirmed.
- Disproportionate: after five refused closes, the allowance stays charged
until the server restarts (`const attempt`,
`packages/ui-backend-claude/src/cleanup-reconciler.ts:78-90`).
until the server restarts (the terminal give-up removed by #3815).
4. **Boot.** A recoverable historical record (a corrupt object, a malformed
intent, an interrupted cleanup) is quarantined and marked, and the host
boots. If it must, it boots restricted, with the unsafe operation still
Expand Down
12 changes: 7 additions & 5 deletions docs/hosting/agent-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,11 +133,13 @@ Recovery copies reserve the existing aggregate output-staging budget in
addition to retained source storage. Closing a handle aborts its pending copy;
the copy reservation remains until that work drains and owned cleanup is
confirmed. An unconfirmed cleanup retains ownership and reservations for
reconciliation rather than reporting successful reclamation. For a Claude
turn's end-of-turn cleanup, the server retries the close a few times with
growing delays and releases the reservation once a retry is confirmed. If
every retry is refused, the server log names the allowance that stays charged
until the server restarts.
reconciliation rather than reporting successful reclamation. For
end-of-turn cleanup, both backends keep retrying with capped backoff
and release the reservation only once a close is confirmed. Pi initialization
failures retain the same retry owner. The original turn's Activity events
record the cleanup cause, retained allowances and eventual confirmation,
including confirmation after the turn has ended. After five failed retries a
host diagnostic reports slow reconciliation; retries continue without a restart.

Files made private are read by fixed, uncredentialed worker-UID code through
authorized retained roots: no repository imports/evaluation, path escapes,
Expand Down
7 changes: 7 additions & 0 deletions docs/http-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -2070,3 +2070,10 @@ principal, generation, finalized-exposure and permanent retirement fences in
the writer and SQLite trigger. Resolving a known event cannot repair unknown
detector coverage, recording loss or another unresolved event. No model/voice
tool, WS mutation frame, Settings rule or provider transcript edit is added.


The authenticated status response also includes `journalCleanup` (#3815):
current retained-checkpoint counts and bytes, plus `lastFailure`, a durable
historical cause even when cleanup failed before the first turn. The historical
record survives successful cleanup; current retained charges are reported
separately. It is never part of public `/health`.
11 changes: 11 additions & 0 deletions docs/integration-contract/http.md
Original file line number Diff line number Diff line change
Expand Up @@ -1088,3 +1088,14 @@ Saved-audio PUT binds `Speech-Provider` before claim/body consumption; absent
headers preserve effective-provider resolution. Retry provider changes return
409 `transcription_provider_mismatch` with the receipt. Settings revisions,
error codes, response schemas and operation binding are supported HTTP promises.


### Checkpoint cleanup diagnostics (additive, #3815)

Authenticated `GET /api/status` adds `journalCleanup`: `retained` contains
`pending`, `failed` and `retainedBytes` for this process's superseded checkpoints;
`lastFailure` is null or the durable historical failure with `kind`,
`checkpointId`, `at` (epoch milliseconds), `scope`, `errorClass`, `cause` and
`retrying: true` at the time it was recorded. The historical cause survives
recovery and restart; it does not assert a currently blocked turn. Current
charges remain separate in `retained`. No field changes public `/health`.
Loading
Loading