diff --git a/.changeset/3793-workspaces-files-changed.md b/.changeset/3793-workspaces-files-changed.md new file mode 100644 index 0000000000..5667dc59dd --- /dev/null +++ b/.changeset/3793-workspaces-files-changed.md @@ -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`. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index d284aa41f6..4d2f8993af 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -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; diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index a056711d9c..be94561c15 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -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. @@ -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. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index f25b176f53..cfa0b80083 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -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, diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index ba07ad39d8..d9dbe8710c 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -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. | diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 34eb56c2d3..20174a2f3a 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -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"; @@ -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(); const failures = new Map(); const failedAdmissions = new Set(); @@ -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, @@ -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"); @@ -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); }; }, diff --git a/packages/ui-server/src/brain/turn-scope.ts b/packages/ui-server/src/brain/turn-scope.ts index e4b2a64d02..a1ebba7506 100644 --- a/packages/ui-server/src/brain/turn-scope.ts +++ b/packages/ui-server/src/brain/turn-scope.ts @@ -14,7 +14,9 @@ import type { TurnJournal } from "./turn-journal.js"; type Worker = Parameters>[0]; type Live = { unrecorded?: boolean; sessionId: string | null; principalId: string; origin: "interactive" | "voice"; profile: "strict" | "governed"; - startedAt: number; summary: TurnScopeSummary; workers: Set; calls: Set; disconnectedAt?: number; + startedAt: number; summary: TurnScopeSummary; + /** What `files_changed` counts: changed paths outside `workspaces/` (#3793); null while unknown. */ + filesChanged: number | null; workers: Set; calls: Set; 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; @@ -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(); @@ -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; @@ -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" }; @@ -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); @@ -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) => { diff --git a/packages/ui-server/tests/helpers/native-journal-fixture.ts b/packages/ui-server/tests/helpers/native-journal-fixture.ts index b979a33225..23cfcdf3f2 100644 --- a/packages/ui-server/tests/helpers/native-journal-fixture.ts +++ b/packages/ui-server/tests/helpers/native-journal-fixture.ts @@ -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({ 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({ 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 }) }; } diff --git a/packages/ui-server/tests/turn-scope-headroom.test.ts b/packages/ui-server/tests/turn-scope-headroom.test.ts index 62e51c7b68..3e3acd8d36 100644 --- a/packages/ui-server/tests/turn-scope-headroom.test.ts +++ b/packages/ui-server/tests/turn-scope-headroom.test.ts @@ -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(); } }; diff --git a/packages/ui-server/tests/turn-scope.test.ts b/packages/ui-server/tests/turn-scope.test.ts index 102b67ecfe..e72131b95f 100644 --- a/packages/ui-server/tests/turn-scope.test.ts +++ b/packages/ui-server/tests/turn-scope.test.ts @@ -65,22 +65,58 @@ test("real process tree freezes, resumes once per dimension, then stops with eve } }); -test("shared snapshots count ignored scratch, workspaces and repeated observed bytes, with independent finite grant", async () => { +test("shared snapshots count ignored scratch, workspace bytes and repeated observed bytes, with independent finite grant", async () => { const f = scopeFixture({ max_bytes_written: 8, max_files_changed: 3 }); let child: ReturnType | undefined; try { await f.begin(); child = f.worker('while :; do sleep 1; done'); writeFileSync(join(f.brain, ".brain/scratch/loom"), "12345678"); await f.journal.observe(); expect(f.receipt()).toMatchObject({ dimension: "turn_bytes", count: 8, cap: 8, newCap: 16 }); expect((await f.scope.decide(f.message("continue"), true)).state).toBe("accepted"); - writeFileSync(join(f.brain, "workspaces/shroud"), "x"); writeFileSync(join(f.brain, "sail"), "x"); await f.journal.observe(); + // The workspace file adds bytes but no changed path (#3793). + writeFileSync(join(f.brain, "workspaces/shroud"), "x"); writeFileSync(join(f.brain, "sail"), "x"); writeFileSync(join(f.brain, "mast"), "x"); await f.journal.observe(); expect(f.receipt()).toMatchObject({ dimension: "files_changed", count: 3, newCap: 6 }); expect((await f.scope.decide(f.message("continue", "files"), true)).state, "SCOPE_OTHER_DIMENSION_RETAINS_GRANT").toBe("accepted"); writeFileSync(join(f.brain, ".brain/scratch/loom"), "87654321"); await f.journal.observe(); - expect(f.receipt()).toMatchObject({ dimension: "turn_bytes", count: 18, cap: 16, overshoot: 2 }); expect(f.receipt().newCap).toBeUndefined(); + expect(f.receipt()).toMatchObject({ dimension: "turn_bytes", count: 19, cap: 16, overshoot: 3 }); expect(f.receipt().newCap).toBeUndefined(); (await f.scope.decide(f.message("stop", "bytes-stop"), true)); await child.exited; } finally { child?.kill("SIGKILL"); if (child) await child.exited; await f.close(); } }); +test("files_changed leaves out a reference clone under workspaces/ but counts every path outside it (#3793)", async () => { + const f = scopeFixture({ max_files_changed: 1000 }); let child: ReturnType | undefined; + try { + await f.begin(); child = f.worker('while :; do sleep 1; done'); + // A fetch and checkout of a mid-sized repository, and nothing in the brain. + mkdirSync(join(f.brain, "workspaces/argo/src"), { recursive: true }); + for (let index = 0; index < 1500; index++) writeFileSync(join(f.brain, "workspaces/argo/src", `oar-${index}.ts`), `export const oar = ${index};\n`); + await f.journal.observe(); + const scope = () => f.journal.summary("voyage").scope!; + expect(scope().receipts, "WORKSPACE_CLONE_DOES_NOT_PAUSE_FILES_CHANGED").toEqual([]); + expect(scope().changedPaths, "SUMMARY_STILL_DISCLOSES_WORKSPACE_PATHS").toBeGreaterThanOrEqual(1500); + for (let index = 0; index < 999; index++) writeFileSync(join(f.brain, `ithaca-${index}.md`), `Day ${index}\n`); + await f.journal.observe(); + expect(scope().receipts, "BRAIN_PATHS_BELOW_THE_CAP_DO_NOT_PAUSE").toEqual([]); + // A sibling sharing the prefix is outside workspaces/ and counts. + mkdirSync(join(f.brain, "workspaces-old")); writeFileSync(join(f.brain, "workspaces-old/x.md"), "Old raft\n"); + writeFileSync(join(f.brain, "ithaca-999.md"), "Day 999\n"); + await f.journal.observe(); + expect(f.receipt(), "BRAIN_PATHS_PAST_THE_CAP_STILL_PAUSE").toMatchObject({ dimension: "files_changed", count: 1001, cap: 1000, state: "paused", frozen: true }); + await f.scope.decide(f.message("stop"), true); await child.exited; + } finally { child?.kill("SIGKILL"); if (child) await child.exited; await f.close(); } +}); + +test("workspace writes still count toward turn_bytes and pause the turn there (#3793)", async () => { + const f = scopeFixture({ max_files_changed: 1, max_bytes_written: 1024 }); let child: ReturnType | undefined; + try { + await f.begin(); child = f.worker('while :; do sleep 1; done'); + mkdirSync(join(f.brain, "workspaces/argo")); + writeFileSync(join(f.brain, "workspaces/argo/hull.bin"), Buffer.alloc(1024, 1)); writeFileSync(join(f.brain, "workspaces/argo/keel.bin"), Buffer.alloc(1024, 2)); + await f.journal.observe(); + expect(f.journal.summary("voyage").scope!.receipts, "WORKSPACE_BYTES_PAUSE_TURN_BYTES_ONLY").toMatchObject([{ dimension: "turn_bytes", count: 2048, cap: 1024, state: "paused" }]); + await f.scope.decide(f.message("stop"), true); await child.exited; + } finally { child?.kill("SIGKILL"); if (child) await child.exited; await f.close(); } +}); + test("repeated ignored 100 MB observations count once per path while hashed rewrites keep their version bytes", async () => { const size = 100_000_000; const f = scopeFixture({ max_bytes_written: size * 2 });