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/3793-workspaces-files-changed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@schlessera/brain-ui-server": minor
---

A governed turn's `files_changed` scope limit no longer counts changed paths under `workspaces/` (#3793). Fetching or checking out a reference clone there could touch more than 1,000 files and pause an interactive turn that changed nothing in the brain. `max_bytes_written` and the free-space floor still count workspace writes, and the turn's scope summary still reports every changed path. A sibling such as `workspaces-old/` still counts. The journal's internal observation facts add `workspacePaths`.
1 change: 1 addition & 0 deletions api-report/ui-server.txt
Original file line number Diff line number Diff line change
Expand Up @@ -2579,6 +2579,7 @@ signatures (every public export and the types it is made of)
changedPaths: number;
observedBytes: number;
partial: boolean;
workspacePaths: number;
}) => void, periodic?: {
after(completed: boolean): void;
before(): void;
Expand Down
11 changes: 9 additions & 2 deletions docs/decisions/governed-writable-workers.md
Original file line number Diff line number Diff line change
Expand Up @@ -1537,7 +1537,13 @@ kept observation, is not retained, just as it was not when no tool result fell
between.

**Scope limits.** `files_changed` and `turn_bytes` are evaluated on each
observation's facts. A proven read changes nothing, so it cannot cross a limit.
observation's facts. `files_changed` counts only changed paths outside
`workspaces/`, by path containment rather than a string prefix, so
`workspaces-old/` still counts. A reference clone fetched or checked out there
touches hundreds of files without changing the brain, and that alone paused
interactive turns. `turn_bytes` and the free-space floor still count every
workspace write, and the journal summary still reports every changed path
(#3793). A proven read changes nothing, so it cannot cross a limit.
A writer's result is still observed, so its own crossing is detected there.
After an unproven call every result is observed, so a limit that a background
writer crosses between two calls is detected at the next result, as before.
Expand Down Expand Up @@ -2181,7 +2187,8 @@ Queue budgets keep their existing admission and containment semantics.

The policy's `scope` limits apply per turn to:

- distinct paths changed in the brain and workspaces;
- distinct paths changed in the brain, outside `workspaces/`;
- bytes written, in the brain and workspaces;
- wall time;
- tool calls.

Expand Down
11 changes: 11 additions & 0 deletions docs/integration-contract/package-api.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,17 @@ A backend that never calls it, and every call it reports nothing for, keeps
the observation after each result. This is first-party implementation sharing
under the internal-entry classification below and requires a patch changeset.

## Workspace paths in turn observation facts (additive, 0.45.0, #3793)

The `onObservation` observer of `createTurnJournal`'s journal, tagged
`@internal` but recorded in `api-report/` because the journal's type is
inferred, receives one more fact: `workspacePaths`, how many of the
observation's `changedPaths` lie below `workspaces/` by path containment.
`changedPaths` still counts every changed path. The host scope monitor caps
`files_changed` at `changedPaths - workspacePaths`; `turn_bytes`, the
free-space floor and the scope summary's `changedPaths` are unchanged. No wire,
HTTP or policy shape changes.

## Managed GitHub acquisition wire (internal #3613)

The internal turn proxy has a first-party `managedReference(target,
Expand Down
2 changes: 1 addition & 1 deletion docs/supported-inputs.md
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ objects merge per field. No value grants authority to autonomous turns.
| `protect` | Array of canonical brain-relative paths | Adds protection. No absolute, home, drive, backslash, empty/dot/parent segment or control-character forms. Default `[]`. |
| `release` | Array of exact built-in tier B paths | Default `[]`; tier A and `.env*` cannot be released. See [the protected tiers](decisions/governed-writable-workers.md#protected-paths). |
| `budgets` | `turn`, `session`, `day`, each with optional `warn_usd`, `block_usd`, `warn_tokens`, `block_tokens` | USD amounts are finite/nonnegative; tokens are nonnegative safe integers. Turn warn/block $100/$200 with 512,000,000 fallback tokens; session/day $2,000/$4,000 with 8,000,000,000 fallback tokens. Day is UTC calendar day; session is retained lifetime. |
| `scope` | `max_files_changed`, `max_minutes`, `max_tool_calls`, `max_bytes_written` | Nonnegative safe integers, except finite minutes. Defaults: 1,000 paths, 120 minutes, 500 calls, 4 GiB. Path/byte defaults are provisional approved values, not measured distributions. |
| `scope` | `max_files_changed`, `max_minutes`, `max_tool_calls`, `max_bytes_written` | Nonnegative safe integers, except finite minutes. Defaults: 1,000 paths, 120 minutes, 500 calls, 4 GiB. `max_files_changed` counts changed paths outside `workspaces/`; `max_bytes_written` counts workspace writes too. Path/byte defaults are provisional approved values, not measured distributions. |
| `commands` | `deny`, `confirm`: arrays of `{ pattern: string, reason?: string }` | Additions to existing permissions, default `[]`. Regex sources preserve their literal anchors and compile case-insensitively under [confirmation rules](decisions/confirm-patterns.md). Mixed lists retain valid entries in order and report skipped sources; nonempty entirely invalid lists refuse. |
| `egress` | `mode`: `record`/`allowlist`; `allow`, `deny`: string arrays; `max_bytes_per_turn`: nonnegative safe integer | `record`, empty lists and no byte cap by default. This reader does not establish network enforcement. |
| `outward` | `allow`: array of `{ command: string, remotes: string[] }`; `hosts`: string array | Default empty additions to the existing outward-action rules and built-in destination list. Parsing grants no action. |
Expand Down
22 changes: 16 additions & 6 deletions packages/ui-server/src/brain/turn-journal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import type { JournalRecoveryStatus } from "@schlessera/brain-ui-sdk/protocol";
import type { Logger } from "@opentelemetry/api-logs";
import { isWithin } from "@schlessera/brain-common/internal/safe-path";
import { BRAIN_WORKSPACES_DIR } from "@schlessera/brain-common/internal/worker-areas";
import type { Database, SQLQueryBindings } from "bun:sqlite";
import type { ConfigurationCoverageRead, JournalVersion, TurnJournalDetails, TurnJournalSummary, JournalOutwardAction, JournalObservationReference } from "@schlessera/brain-ui-sdk/protocol";
import { recordedConfigurationSet } from "./journal-configuration-sets.js";
Expand Down Expand Up @@ -274,7 +275,7 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) {
}
}
const periodicObservers = new Set<{ before(): void; after(completed: boolean): void }>();
const observers = new Set<(turnId: string, facts: { changedPaths: number; observedBytes: number; partial: boolean }) => void>();
const observers = new Set<(turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; partial: boolean }) => void>();
const pendingReadReleases = new Set<string>();
const failures = new Map<string, string>();
const failedAdmissions = new Set<string>();
Expand Down Expand Up @@ -488,7 +489,11 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) {
// versions. The disposable index is counted the same way, ignored or not,
// including history recorded before it became metadata-only (#2873). A
// host publication copy of it is no turn write once it is gone (#2831).
const facts = db.query(`SELECT count(*) AS changedPaths,coalesce(sum(hashedBytes+ignoredBytes),0) AS observedBytes FROM (
// Workspace paths are counted separately so the scope monitor can leave
// reference clones out of files_changed (#3793). GLOB only narrows the
// candidates; containment is isWithin's, so `workspaces-old/` stays out.
const facts = db.query(`SELECT count(*) AS changedPaths,coalesce(sum(hashedBytes+ignoredBytes),0) AS observedBytes,
json_group_array(path) FILTER (WHERE path GLOB ?) AS workspaceCandidates FROM (
SELECT path,sum(CASE WHEN json_extract(after_json,'$.kind')='file' AND coalesce(json_extract(after_json,'$.ignored'),0)!=1 AND NOT disposable
AND json_extract(after_json,'$.hash') IS NOT json_extract(before_json,'$.hash')
THEN json_extract(after_json,'$.bytes') ELSE 0 END) AS hashedBytes,
Expand All @@ -497,8 +502,9 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) {
FROM (SELECT *,(path IN (SELECT value FROM json_each(?)) OR coalesce(json_extract(after_json,'$.metadataOnly'),0)=1) AS disposable FROM turn_journal_changes AS change
WHERE turn_id=? AND NOT (path GLOB ? AND (SELECT after_json FROM turn_journal_changes WHERE turn_id=change.turn_id
AND path=change.path ORDER BY sequence DESC LIMIT 1) IS NULL)) GROUP BY path
)`).get(DISPOSABLE_INDEX_PATHS, turnId, INDEX_PUBLICATION_COPY) as { changedPaths: number; observedBytes: number };
for (const observer of observers) observer(turnId, { ...facts, partial: summary(turnId).state === "partial" });
)`).get(`${BRAIN_WORKSPACES_DIR}*`, DISPOSABLE_INDEX_PATHS, turnId, INDEX_PUBLICATION_COPY) as { changedPaths: number; observedBytes: number; workspaceCandidates: string };
const workspacePaths = (JSON.parse(facts.workspaceCandidates) as string[]).filter(path => isWithin(BRAIN_WORKSPACES_DIR, path, { includeRoot: false })).length;
for (const observer of observers) observer(turnId, { changedPaths: facts.changedPaths, observedBytes: facts.observedBytes, workspacePaths, partial: summary(turnId).state === "partial" });
step?.();
}
const committed = timing?.("observe_commit");
Expand All @@ -515,8 +521,12 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) {
}
}
return {
/** @internal Host scope monitor consumes this same observation window. */
onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; partial: boolean }) => void, periodic?: { before(): void; after(completed: boolean): void }) {
/**
* @internal Host scope monitor consumes this same observation window.
* `changedPaths` counts every changed path; `workspacePaths` is how many
* of them lie below `workspaces/` (#3793).
*/
onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; workspacePaths: number; partial: boolean }) => void, periodic?: { before(): void; after(completed: boolean): void }) {
observers.add(observer); if (periodic) periodicObservers.add(periodic);
return () => { if (periodic) periodicObservers.delete(periodic); return observers.delete(observer); };
},
Expand Down
15 changes: 10 additions & 5 deletions packages/ui-server/src/brain/turn-scope.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@ import type { TurnJournal } from "./turn-journal.js";

type Worker = Parameters<NonNullable<StartTurnRequest["workerStarted"]>>[0];
type Live = { unrecorded?: boolean; sessionId: string | null; principalId: string; origin: "interactive" | "voice"; profile: "strict" | "governed";
startedAt: number; summary: TurnScopeSummary; workers: Set<Worker>; calls: Set<string>; disconnectedAt?: number;
startedAt: number; summary: TurnScopeSummary;
/** What `files_changed` counts: changed paths outside `workspaces/` (#3793); null while unknown. */
filesChanged: number | null; workers: Set<Worker>; calls: Set<string>; disconnectedAt?: number;
checking?: boolean; source: "policy" | "default"; stop: (reason: string) => void; current: () => boolean; model?: () => string | null };
export const SCOPE_DISCONNECTED_MS = 30 * 60_000;
export const SCOPE_FREE_BYTES = 2 * 1024 ** 3;
Expand Down Expand Up @@ -75,7 +77,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour
if (receipt.dimension === "free_space_floor") return;
const dimension = receipt.dimension;
const observed = dimension === "tool_calls" ? turn.summary.calls : dimension === "minutes" ? turn.summary.minutes
: dimension === "files_changed" ? turn.summary.changedPaths : turn.summary.observedBytes;
: dimension === "files_changed" ? turn.filesChanged : turn.summary.observedBytes;
// Incomplete captures retain the last reliable receipt, never imply headroom.
if (observed !== null && Number.isFinite(observed)) {
receipt.count = observed; receipt.overshoot = Math.max(0, observed - receipt.cap); receipt.observedAt = now();
Expand Down Expand Up @@ -114,7 +116,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour
}
if (turn.checking) return;
const counts: [ScopeDimension, number | null][] = [["free_space_floor", fs.free], ["tool_calls", turn.summary.calls],
["minutes", turn.summary.minutes], ["files_changed", turn.summary.changedPaths], ["turn_bytes", turn.summary.observedBytes]];
["minutes", turn.summary.minutes], ["files_changed", turn.filesChanged], ["turn_bytes", turn.summary.observedBytes]];
for (const [dimension, count] of counts) {
const cap = dimension === "free_space_floor" ? floor : turn.summary.limits[dimension];
if (count === null || (dimension === "free_space_floor" ? count >= cap : count < cap)) continue;
Expand All @@ -132,7 +134,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour
}
turn.summary.minutes = Math.max(0, (now() - turn.startedAt) / 60_000);
const measured = dimension === "tool_calls" ? turn.summary.calls : dimension === "minutes" ? turn.summary.minutes
: dimension === "files_changed" ? turn.summary.changedPaths : dimension === "turn_bytes" ? turn.summary.observedBytes : space().free;
: dimension === "files_changed" ? turn.filesChanged : dimension === "turn_bytes" ? turn.summary.observedBytes : space().free;
const observed = measured ?? count;
const receipt: ScopeCapReceipt = { eventId: randomUUID(), dimension, count: observed, cap,
overshoot: Math.max(0, dimension === "free_space_floor" ? cap - observed : observed - cap), frozen, observedAt: now(), state: "paused" };
Expand Down Expand Up @@ -189,7 +191,10 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour
};
const unsubscribe = options.journal.onObservation((turnId, facts) => {
const turn = active.get(turnId); if (!turn) return;
// The summary discloses every changed path; files_changed leaves out the
// workspaces/ scratch, which turn_bytes and the free-space floor still bound.
turn.summary.changedPaths = facts.partial ? null : facts.changedPaths;
turn.filesChanged = facts.partial ? null : facts.changedPaths - facts.workspacePaths;
turn.summary.observedBytes = facts.partial ? null : facts.observedBytes;
turn.summary.coverage = facts.partial ? "partial" : "observed_versions";
turn.summary.observedAt = now(); check(turnId, turn);
Expand All @@ -199,7 +204,7 @@ export function createTurnScope(db: Database, options: { brainPath: string; jour
policy: EffectiveGovernancePolicy; source: Live["source"]; hardTimeoutMs: number; current: () => boolean; model?: () => string | null; stop: Live["stop"] }) {
const summary: TurnScopeSummary = { policySource: input.source, limits: scopeLimits(input.policy), hardTimeoutMs: input.hardTimeoutMs, calls: 0, minutes: 0,
changedPaths: null, observedBytes: null, coverage: "partial", observedAt: now(), receipts: [] };
const turn: Live = { ...input, startedAt: now(), summary, workers: new Set(), calls: new Set() };
const turn: Live = { ...input, startedAt: now(), summary, filesChanged: null, workers: new Set(), calls: new Set() };
active.set(turnId, turn);
// The turn starts only once its row has committed; refused, it never runs.
return call(turnId, "insert", input.sessionId, input.principalId, JSON.stringify(summary)).then(() => {}, (error: unknown) => {
Expand Down
6 changes: 5 additions & 1 deletion packages/ui-server/tests/helpers/native-journal-fixture.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,11 @@ export function fixtureDelta(before: { uuid: string; transaction: string; entrie
else records.push(command(22, [[15, bytes(path)], [18, u64(0n)], [4, u64(BigInt(current.bytes))]]));
}
const raw = Buffer.concat([bytes("btrfs-stream\0"), Buffer.from([1, 0, 0, 0]), ...records, command(21)]);
const stream = new ReadableStream<Uint8Array>({ start(controller) { controller.enqueue(raw); controller.close(); } });
// Bounded chunks, as the native manager streams them: a large delta is never one oversized chunk.
const stream = new ReadableStream<Uint8Array>({ start(controller) {
for (let offset = 0; offset < raw.length; offset += NATIVE_DATA_CHUNK_BYTES) controller.enqueue(raw.subarray(offset, offset + NATIVE_DATA_CHUNK_BYTES));
controller.close();
} });
return { stream, completed: Promise.resolve({ exitCode: 0 as const, bytes: raw.byteLength }) };
}

Expand Down
2 changes: 1 addition & 1 deletion packages/ui-server/tests/turn-scope-headroom.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ function fixture(origin: "interactive" | "voice" = "interactive") {
const summary = () => JSON.parse((db.query("SELECT summary FROM turn_scope WHERE turn_id='voyage'").get() as { summary: string }).summary) as TurnScopeSummary;
const receipt = () => summary().receipts.at(-1)!;
const observe = (count: number, dimension: "files_changed" | "turn_bytes" = "files_changed", partial = false) => {
periodic.before(); observer("voyage", { changedPaths: dimension === "files_changed" ? count : 0, observedBytes: dimension === "turn_bytes" ? count : 0, partial }); periodic.after(true);
periodic.before(); observer("voyage", { changedPaths: dimension === "files_changed" ? count : 0, observedBytes: dimension === "turn_bytes" ? count : 0, workspacePaths: 0, partial }); periodic.after(true);
};
const message = (action: ClientScopeDecision["action"] = "continue", submissionId = "athena-grant"): ClientScopeDecision => ({ type: "scope_decision", sessionId: "ithaca", turnId: "voyage", eventId: receipt().eventId, submissionId, action });
return { db, scope, summary, receipt, observe, message, get callbacks() { return { freezes, resumes, kills }; }, advance(ms: number) { clock += ms; }, disconnect() { connected = false; }, end() { current = false; }, floor() { free = 0; }, close() { scope.close(); db.close(); } };
Expand Down
Loading
Loading