From a9bf56c81f23baf8ed41fd4da3e23b65aab33bc8 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:52:57 +0000 Subject: [PATCH 01/21] feat(ui-server): review a sync's incoming governance policy change instead of failing (#4256) Co-Authored-By: Claude Opus 5.5 --- packages/ui-sdk/src/internal.ts | 1 + .../src/server/protected-output-error.ts | 22 +++ .../ui-sdk/src/server/worker-native-output.ts | 37 ++++ packages/ui-server/src/apify/settings.ts | 82 ++------- packages/ui-server/src/app.ts | 9 +- packages/ui-server/src/brain/host-boundary.ts | 10 +- .../src/brain/owner-policy-reviews.ts | 134 ++++++++++++++ packages/ui-server/src/brain/sync-mirror.ts | 78 ++++++++- packages/ui-server/src/routes/brain.ts | 61 ++++++- .../tests/sync-policy-review.test.ts | 164 ++++++++++++++++++ 10 files changed, 514 insertions(+), 84 deletions(-) create mode 100644 packages/ui-sdk/src/server/protected-output-error.ts create mode 100644 packages/ui-server/src/brain/owner-policy-reviews.ts create mode 100644 packages/ui-server/tests/sync-policy-review.test.ts diff --git a/packages/ui-sdk/src/internal.ts b/packages/ui-sdk/src/internal.ts index 44bcea5be9..d6a4ecb9ac 100644 --- a/packages/ui-sdk/src/internal.ts +++ b/packages/ui-sdk/src/internal.ts @@ -72,6 +72,7 @@ export { parseNativeBrainDelta } from "./server/native-brain-delta.js"; export type { NativeBrainDeltaCandidate } from "./server/native-brain-delta.js"; export { prepareNativeWorkerOutput, type PreparedWorkerOutput, type WorkerOutputStorage } from "./server/worker-native-output.js"; +export { ProtectedMaintenanceOutputError } from "./server/protected-output-error.js"; export { createNativeBrainManagerClient } from "./server/native-brain-manager-client.js"; export { NATIVE_MANAGER_OPERATION_TIMEOUT_MS, NATIVE_MANAGER_MAX_DELTA_BYTES, NativeBrainManagerError } from "./server/native-brain-manager-protocol.js"; diff --git a/packages/ui-sdk/src/server/protected-output-error.ts b/packages/ui-sdk/src/server/protected-output-error.ts new file mode 100644 index 0000000000..febfb6d228 --- /dev/null +++ b/packages/ui-sdk/src/server/protected-output-error.ts @@ -0,0 +1,22 @@ +/** + * A maintenance output refused because it changes tier A inputs (#4256). + * Publication is refused exactly as before; the error also names every + * protected path the output changed and, while the output still exists, lets + * the host read one of those files so it can decide what to do with an + * incoming change. It never writes anything and grants nothing. + */ +export class ProtectedMaintenanceOutputError extends Error { + constructor( + /** Every changed path the tier A rule refuses, sorted. */ + readonly paths: readonly string[], + /** + * The output's bytes of one refused path: null when it is absent or not a + * regular file, a refusal when larger than `bound`. Valid only until the + * output is cleaned up. + */ + readonly read: (rel: string, bound: number) => Promise, + ) { + super(`maintenance output cannot change protected input ${paths[0]}`); + this.name = "ProtectedMaintenanceOutputError"; + } +} diff --git a/packages/ui-sdk/src/server/worker-native-output.ts b/packages/ui-sdk/src/server/worker-native-output.ts index 24d6092616..1c25017b00 100644 --- a/packages/ui-sdk/src/server/worker-native-output.ts +++ b/packages/ui-sdk/src/server/worker-native-output.ts @@ -9,6 +9,7 @@ import { hostOutputStagingLimits } from "./worker-state-limits.js"; import { WorkerStateError, processStateLedger } from "./worker-state-budget.js"; import { nativeWorkerStartupInput, retainWorkerStartupView, type WorkerStartupView } from "./worker-startup-view.js"; import { isEnvName, PROTECTED_TIER_A } from "./protected-paths.js"; +import { ProtectedMaintenanceOutputError } from "./protected-output-error.js"; import { FIRST_PARTY_FAILURE_CLASSES } from "../protocol.js"; import type { KeyedLock } from "./keyed-lock.js"; import { NativeBrainManagerError, type NativeStage } from "./native-brain-manager-protocol.js"; @@ -337,6 +338,34 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu if ((await privateStat(stageInput, rel))?.stamp !== info.stamp) throw Error("Native private output changed while hashing"); return { entry: { type: "file", mode: info.mode, hash: hash.digest("hex") }, stamp: version }; } + /** One refused output file's bytes for the host, bounded; null when absent or not a regular file. */ + async function readRefused(rel: string, bound: number): Promise { + if ((await inspectInput(true, rel)).entry?.type !== "file") return null; + const direct = async () => { + const chunks: Buffer[] = []; let total = 0; + const handle = parent(output.source, rel); + try { + const file = await open(at(handle.fd, handle.name), FILE); + try { + const buffer = Buffer.alloc(64 * 1024); + for (;;) { + const { bytesRead } = await file.read(buffer); if (!bytesRead) break; + total += bytesRead; if (total > bound) throw Error(`Refused output ${rel} exceeds ${bound} bytes`); + chunks.push(Buffer.from(buffer.subarray(0, bytesRead))); + } + } finally { await file.close(); } + } finally { closeSync(handle.fd); } + return Buffer.concat(chunks); + }; + try { return await direct(); } + catch (error) { if (!identityTicket || !permissionDenied(error)) throw error; } + const chunks: Buffer[] = []; let total = 0; + await privateBytes(true, rel, async bytes => { + total += bytes.byteLength; if (total > bound) throw Error(`Refused output ${rel} exceeds ${bound} bytes`); + chunks.push(Buffer.from(bytes)); + }, bound + 1); + return Buffer.concat(chunks); + } async function walIndexInput(stageInput: boolean): Promise { try { return { entry: walIndexEntry(stageInput ? output.source : view.root, WAL_INDEX), stamp: undefined }; } catch (error) { if (!identityTicket || !permissionDenied(error)) throw error; } @@ -402,6 +431,14 @@ export async function prepareNativeWorkerOutput(brain: string, options: { startu before.set(WAL_INDEX, await walIndexInput(false)); after.set(WAL_INDEX, await walIndexInput(true)); changed.push(WAL_INDEX); changed.sort(); } + // Every refused tier A change, named before any lock or write (#4256). + const refused = changed.filter(rel => { + const previous = before.get(rel)!.entry, next = after.get(rel)!.entry; + const removesProtectedAncestor = previous?.type === "directory" && !next + && PROTECTED_TIER_A.some(p => isWithin(rel, p, { includeRoot: false })); + return removesProtectedAncestor || isEnvName(rel.split("/")[0]!) || PROTECTED_TIER_A.some(p => isWithin(p, rel)); + }); + if (refused.length) throw new ProtectedMaintenanceOutputError(refused, (rel, bound) => readRefused(rel, bound)); const releases: (() => void)[] = []; try { if (lock) for (const rel of [...new Set([...changed, ...[...gitScaffolds.keys()].map(name => `.git/${name}`)])].sort()) diff --git a/packages/ui-server/src/apify/settings.ts b/packages/ui-server/src/apify/settings.ts index d2653ab029..d617a99fd0 100644 --- a/packages/ui-server/src/apify/settings.ts +++ b/packages/ui-server/src/apify/settings.ts @@ -14,9 +14,8 @@ * user-history operation. The control itself never writes. Only the owner who * proposed a change can decide it; agents never reach these routes. */ -import { createHash, randomUUID } from "node:crypto"; -import { existsSync, readFileSync } from "node:fs"; -import { join } from "node:path"; +import { createHash } from "node:crypto"; +import { existsSync } from "node:fs"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { checkGovernancePolicy, GOVERNANCE_POLICY_PATH } from "@schlessera/brain-common/internal/governance-policy"; import { liability, type ApifyLedger, type ApifyRuns, type ApifyStatus, type ApifyCoverageScope } from "@schlessera/brain-common/internal/apify"; @@ -25,7 +24,8 @@ import type { ApifyGrantRead, ApifyPolicyChange, ApifyPolicyMode, ApifyPolicyProposalRead, ApifyPolicyRead, ApifySettingsRead, ApifySpendRead, ApifySpendScopeRead, ApifyUnresolvedRunRead, } from "@schlessera/brain-ui-sdk/protocol"; -import type { PolicyProposals, PolicyProposalTurn } from "../brain/policy-proposal.js"; +import type { PolicyProposals } from "../brain/policy-proposal.js"; +import { createOwnerPolicyReviews, type OwnerPolicyJournal } from "../brain/owner-policy-reviews.js"; /** A refusal with an HTTP status and a fixed message; it never carries policy text or a secret. */ export class ApifySettingsError extends Error { @@ -232,10 +232,7 @@ export function apifySettingsRead(status: ApifyStatus, policy: ApifyPolicyRead, } /** The `user` journal window a settings edit is written in, as for any user-history operation. */ -export interface ApifySettingsJournal { - begin(turnId: string, metadata: { sessionId: null; actor: "user"; model: null; profile: "strict"; policyHash: string | null }, stop: (error: Error) => void, signal?: AbortSignal): Promise; - finish(turnId: string): Promise; -} +export type ApifySettingsJournal = OwnerPolicyJournal; interface ApifyPolicyEditsOptions { root: string; @@ -247,79 +244,22 @@ interface ApifyPolicyEditsOptions { timeoutMs?: number; } -/** At most this many unanswered Settings reviews per owner. */ -const MAX_PENDING = 4; - export function createApifyPolicyEdits(options: ApifyPolicyEditsOptions) { - const timeoutMs = options.timeoutMs ?? 10 * 60_000; - const pending = new Map }>(); - const read = (): string | null => { - try { return readFileSync(join(options.root, GOVERNANCE_POLICY_PATH), "utf8"); } - catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; } - }; + const reviews = createOwnerPolicyReviews({ ...options, turnPrefix: "settings-apify", requestPrefix: "apify", + fail: (status, code, message) => new ApifySettingsError(status, code, code === "stale" ? "The policy changed since Settings read it. Reload Settings; nothing was proposed." : message) }); return { /** Propose one change against the policy version the owner saw; resolves once its review is pending. */ async propose(principalId: string, change: ApifyPolicyChange, baseHash: string | null): Promise { - if (!options.authorized(principalId)) throw new ApifySettingsError(409, "not_authorized", "This owner no longer has current authority. Nothing was proposed."); - if ([...pending.values()].filter(entry => entry.principalId === principalId).length >= MAX_PENDING) - throw new ApifySettingsError(409, "busy", "Answer the open policy reviews first. Nothing was proposed."); - const current = read(); - const hash = current === null ? null : createHash("sha256").update(current, "utf8").digest("hex"); - if (hash !== baseHash) throw new ApifySettingsError(409, "stale", "The policy changed since Settings read it. Reload Settings; nothing was proposed."); - const content = editApifyPolicy(current, change); - const turnId = `settings-apify-${randomUUID()}`, requestId = `apify-${randomUUID()}`, key = `${turnId}:${requestId}`; - const controller = new AbortController(); - let answer!: (approve: boolean) => void; - const decision = new Promise(resolve => { answer = resolve; }); - let shown!: (review: PolicyChangeReview) => void, failed!: (error: unknown) => void; - const first = new Promise((resolve, reject) => { shown = resolve; failed = reject; }); - let journaled = false; - const timer = setTimeout(() => answer(false), timeoutMs); - timer.unref?.(); - const turn: PolicyProposalTurn = { - principalId, turnId, sessionId: () => null, signal: controller.signal, - isAuthorized: () => options.authorized(principalId), isAvailable: () => true, - approve: async review => { - shown(structuredClone(review)); - if (!await decision) return false; - // Approved: the write happens inside a user journal window, like a revert or a removal. - await options.journal.begin(turnId, { sessionId: null, actor: "user", model: null, profile: "strict", policyHash: review.baseHash }, - () => controller.abort(), controller.signal); - journaled = true; - return true; - }, - emit: () => undefined, - }; - const done = options.proposals.propose(turn, requestId, { content, rationale: apifyChangeRationale(change) }).finally(async () => { - clearTimeout(timer); - pending.delete(key); - if (journaled) await options.journal.finish(turnId).catch(() => undefined); - }); - done.then(review => shown(review), failed); - pending.set(key, { principalId, answer, done }); - try { return { turn_id: turnId, request_id: requestId, review: await first }; } - catch (error) { - answer(false); - throw error instanceof ApifySettingsError ? error : new ApifySettingsError(422, "policy_invalid", - `The proposed policy did not validate, so nothing was proposed: ${error instanceof Error ? error.message.slice(0, 300) : "unknown error"}`); - } + return reviews.propose(principalId, current => editApifyPolicy(current, change), baseHash, apifyChangeRationale(change), + "The proposed policy did not validate, so nothing was proposed"); }, /** * The owner's one answer to a review they proposed. A repeated or late * answer reads the recorded outcome; it never writes again. */ - async decide(principalId: string, turnId: string, requestId: string, approve: boolean): Promise { - const entry = pending.get(`${turnId}:${requestId}`); - if (entry && entry.principalId === principalId) { - entry.answer(approve); - return structuredClone(await entry.done); - } - const recorded = options.proposals.read(principalId, turnId, requestId); - if (!recorded) throw new ApifySettingsError(404, "not_found", "No policy review is open for this request."); - return recorded; - }, + decide: reviews.decide, /** Decline every open review: shutdown or test teardown. */ - close() { for (const entry of pending.values()) entry.answer(false); }, + close: reviews.close, }; } export type ApifyPolicyEdits = ReturnType; diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index d31219f3a7..1784a862ea 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -62,6 +62,7 @@ import type { WorkerHostMode } from "./activity/runtime-status.js"; import { createNativeBrainManagerClient, PROVIDER_CACHE_FILES, resolveWebSearchConfigPath, workerLimitsStatus, type WorkerHostProbe } from "@schlessera/brain-ui-sdk/internal"; import type { WorkerHostStatus } from "@schlessera/brain-ui-sdk/protocol"; import { createBrainRoutes } from "./routes/brain.js"; +import { createOwnerPolicyReviews, OwnerPolicyReviewError } from "./brain/owner-policy-reviews.js"; import { createSessionProfiles } from "./ws/session-profiles.js"; import { createSessionProfileRoutes } from "./routes/session-profiles.js"; import { createSessionRoutes } from "./routes/sessions.js"; @@ -1185,9 +1186,15 @@ export async function createApp(options: CreateAppOptions = {}): Promise { const principal = resolvePrincipal(db, id); return !!principal && ["owner", "ambient"].includes(principal.kind) && isUsablePrincipal(principal, Date.now()); }; + const syncPolicyReviews = createOwnerPolicyReviews({ root: config.brainPath, proposals: policyProposals, journal, authorized: policyOwner, + turnPrefix: "sync-policy", requestPrefix: "sync", fail: (status, code, message) => new OwnerPolicyReviewError(status, code, message) }); + bootCleanup.push(() => syncPolicyReviews.close()); app.route( "/api", - createBrainRoutes({ syncingRoots: new Map(), activity: activity.store, brain, brainPath: config.brainPath, exec: config.exec, keyterms, brainCliMinimum, log: brainLog, boundary }) + createBrainRoutes({ syncingRoots: new Map(), activity: activity.store, policyReviews: syncPolicyReviews, brain, brainPath: config.brainPath, exec: config.exec, keyterms, brainCliMinimum, log: brainLog, boundary }) ); app.route("/api", createSessionProfileRoutes(sessionProfiles)); app.route("/api", createSessionRoutes({ registry, db, labels: host.labels !== null, prepareHistory: (id, messages) => host.prepareHistory(id, messages), diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index e2bed21be8..4333ee10ee 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -89,6 +89,12 @@ export interface BrainExecution { writeFiles?: readonly string[]; /** A complete hosted sync: its only credentialed part is the host mirror transport. */ sync?: boolean; + /** + * @internal A hosted sync whose pull changes only the governance policy + * hands the incoming bytes here instead of failing (#4256); it publishes + * nothing either way. Absent: the sync refuses and names the waiting change. + */ + onPolicyChange?: (change: import("./sync-mirror.js").IncomingPolicyChange) => void; /** * @internal Host-fetched repositories a module cron job may read (#3380): each * mirror read-only, with a Git URL rewrite onto it. Never a credential. @@ -648,7 +654,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { } return credentialed(admission, async () => { if (execution.sync) return outputLock.withLock(brain, () => runMirrorSync({ log: options.log, nativeManager: options.nativeManager, folderPaths: hold?.folderPaths, command: command(execution), transportEnv: execution.env, mirror: mirror ??= syncMirrorPath(brain, options.dbPath), - ...(execution.signal ? { signal: execution.signal } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }), { signal: admissionSignal }); + ...(execution.onPolicyChange ? { onPolicyChange: execution.onPolicyChange } : {}), ...(execution.signal ? { signal: execution.signal } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }), { signal: admissionSignal }); const run = async () => { admissionSignal?.throwIfAborted(); execution.assertAuthorized?.(); @@ -724,7 +730,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { const onAbort = () => abort.abort(execution.signal?.reason); execution.signal?.addEventListener("abort", onAbort, { once: true }); const exited = runMirrorSync({ log: options.log, nativeManager: options.nativeManager, folderPaths: hold?.folderPaths, command: selectedCommand, transportEnv: execution.env, mirror: selectedMirror, signal: abort.signal, - ...(execution.onExecute ? { onExecute: execution.onExecute } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { + ...(execution.onExecute ? { onExecute: execution.onExecute } : {}), ...(execution.onPolicyChange ? { onPolicyChange: execution.onPolicyChange } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { stdout.write(result.stdout); stderr.write(result.stderr); return result.exitCode; }, error => { stderr.write(error instanceof Error ? error.message : String(error)); return 1; }) .finally(async () => { diff --git a/packages/ui-server/src/brain/owner-policy-reviews.ts b/packages/ui-server/src/brain/owner-policy-reviews.ts new file mode 100644 index 0000000000..1be98db410 --- /dev/null +++ b/packages/ui-server/src/brain/owner-policy-reviews.ts @@ -0,0 +1,134 @@ +/** + * Host-owned policy reviews that no agent proposes: Settings › Apify (#3163) + * and an incoming policy change from a sync's pull (#4256). + * + * This adds no policy writer. A review hands complete proposed + * `governance.md` content to the existing policy proposals + * (`createPolicyProposals`), the only privileged policy writer. The owner who + * opened the review approves or declines that exact review, and only an + * approval writes it, inside a `user` journal window like any other + * user-history operation. Agents never reach these reviews. + */ +import { createHash, randomUUID } from "node:crypto"; +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +import { GOVERNANCE_POLICY_PATH } from "@schlessera/brain-common/internal/governance-policy"; +import type { PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { PolicyProposals, PolicyProposalTurn } from "./policy-proposal.js"; + +/** The `user` journal window a host-owned review's approved write happens in. */ +export interface OwnerPolicyJournal { + begin(turnId: string, metadata: { sessionId: null; actor: "user"; model: null; profile: "strict"; policyHash: string | null }, stop: (error: Error) => void, signal?: AbortSignal): Promise; + finish(turnId: string): Promise; +} + +/** A review the owner can decide: its identity and the review as first shown. */ +export interface OwnerPolicyProposal { turn_id: string; request_id: string; review: PolicyChangeReview } + +export type OwnerPolicyRefusal = "not_authorized" | "busy" | "stale" | "policy_invalid" | "not_found"; + +/** A refused review request, with its HTTP status and a fixed message; it never carries policy text. */ +export class OwnerPolicyReviewError extends Error { + constructor(readonly status: 404 | 409 | 422, readonly code: OwnerPolicyRefusal, message: string) { + super(message); + this.name = "OwnerPolicyReviewError"; + } +} + +export interface OwnerPolicyReviewOptions { + root: string; + proposals: PolicyProposals; + journal: OwnerPolicyJournal; + /** The live human-owner check; a review loses its approval the moment it fails. */ + authorized(principalId: string): boolean; + /** Synthetic turn and request id prefixes, naming where the review came from. */ + turnPrefix: string; + requestPrefix: string; + /** The caller's refusal, with its HTTP status and fixed message. */ + fail(status: 404 | 409 | 422, code: OwnerPolicyRefusal, message: string): Error; + /** How long an unanswered review stays open before it is declined. */ + timeoutMs?: number; +} + +/** At most this many unanswered reviews per owner, per review family. */ +const MAX_PENDING = 4; + +export function readGovernancePolicy(root: string): string | null { + try { return readFileSync(join(root, GOVERNANCE_POLICY_PATH), "utf8"); } + catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; } +} + +export const policyHash = (text: string | null) => text === null ? null : createHash("sha256").update(text, "utf8").digest("hex"); + +export function createOwnerPolicyReviews(options: OwnerPolicyReviewOptions) { + const timeoutMs = options.timeoutMs ?? 10 * 60_000; + const pending = new Map }>(); + return { + /** + * Open one review of the complete content `next` makes from the current + * policy. With a `baseHash`, the current policy must still be that + * version. Resolves once the review is pending. + */ + async propose(principalId: string, next: (current: string | null) => string, baseHash: string | null | undefined, rationale: string, + invalid: string): Promise { + if (!options.authorized(principalId)) throw options.fail(409, "not_authorized", "This owner no longer has current authority. Nothing was proposed."); + if ([...pending.values()].filter(entry => entry.principalId === principalId).length >= MAX_PENDING) + throw options.fail(409, "busy", "Answer the open policy reviews first. Nothing was proposed."); + const current = readGovernancePolicy(options.root); + if (baseHash !== undefined && policyHash(current) !== baseHash) throw options.fail(409, "stale", "The policy changed since it was read. Reload; nothing was proposed."); + const content = next(current); + const turnId = `${options.turnPrefix}-${randomUUID()}`, requestId = `${options.requestPrefix}-${randomUUID()}`, key = `${turnId}:${requestId}`; + const controller = new AbortController(); + let answer!: (approve: boolean) => void; + const decision = new Promise(resolve => { answer = resolve; }); + let shown!: (review: PolicyChangeReview) => void, failed!: (error: unknown) => void; + const first = new Promise((resolve, reject) => { shown = resolve; failed = reject; }); + let journaled = false; + const timer = setTimeout(() => answer(false), timeoutMs); + timer.unref?.(); + const turn: PolicyProposalTurn = { + principalId, turnId, sessionId: () => null, signal: controller.signal, + isAuthorized: () => options.authorized(principalId), isAvailable: () => true, + approve: async review => { + shown(structuredClone(review)); + if (!await decision) return false; + // Approved: the write happens inside a user journal window, like a revert or a removal. + await options.journal.begin(turnId, { sessionId: null, actor: "user", model: null, profile: "strict", policyHash: review.baseHash }, + () => controller.abort(), controller.signal); + journaled = true; + return true; + }, + emit: () => undefined, + }; + const done = options.proposals.propose(turn, requestId, { content, rationale }).finally(async () => { + clearTimeout(timer); + pending.delete(key); + if (journaled) await options.journal.finish(turnId).catch(() => undefined); + }); + done.then(review => shown(review), failed); + pending.set(key, { principalId, answer, done }); + try { return { turn_id: turnId, request_id: requestId, review: await first }; } + catch (error) { + answer(false); + throw options.fail(422, "policy_invalid", `${invalid}: ${error instanceof Error ? error.message.slice(0, 300) : "unknown error"}`); + } + }, + /** + * The owner's one answer to a review they opened. A repeated or late + * answer reads the recorded outcome; it never writes again. + */ + async decide(principalId: string, turnId: string, requestId: string, approve: boolean): Promise { + const entry = pending.get(`${turnId}:${requestId}`); + if (entry && entry.principalId === principalId) { + entry.answer(approve); + return structuredClone(await entry.done); + } + const recorded = turnId.startsWith(`${options.turnPrefix}-`) ? options.proposals.read(principalId, turnId, requestId) : null; + if (!recorded) throw options.fail(404, "not_found", "No policy review is open for this request."); + return recorded; + }, + /** Decline every open review: shutdown or test teardown. */ + close() { for (const entry of pending.values()) entry.answer(false); }, + }; +} +export type OwnerPolicyReviews = ReturnType; diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index dc914bb98e..c29be7e741 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -5,11 +5,12 @@ * brain. The caller holds the exclusive writer gate for the entire workflow. */ import { createHash } from "node:crypto"; -import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, realpathSync, writeFileSync } from "node:fs"; +import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, realpathSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { dirname, join, resolve } from "node:path"; import { isWithin } from "@schlessera/brain-common/internal/safe-path"; -import { runMaintenanceWorker, prepareNativeWorkerStartupView, type MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; +import { runMaintenanceWorker, prepareNativeWorkerStartupView, ProtectedMaintenanceOutputError, type MaintenanceCommand } from "@schlessera/brain-ui-sdk/internal"; +import { GOVERNANCE_POLICY_PATH } from "@schlessera/brain-common/internal/governance-policy"; import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; import { prepareMaintenanceOutput } from "./maintenance-output.js"; import { prepareMaintenanceGit } from "./maintenance-git.js"; @@ -133,7 +134,45 @@ export function syncTransportCommand(input: { brain: string; mirror: string; rem } /** Execute repository code from immutable inputs and publish validated outputs before transport. */ -async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal; timeoutMs?: number }, nativeManager: Parameters[1] | undefined, folderPaths?: readonly string[], log?: import("@opentelemetry/api-logs").Logger): Promise { +/** + * A pull that changes the governance policy (#4256): the incoming bytes and + * the upstream commit they arrived with. Nothing was published; the owner + * reviews the change, and only an approval writes it, through the policy writer. + */ +export interface IncomingPolicyChange { content: Uint8Array; upstream: string | null } +/** Larger than the policy writer's 1 MiB bound, so an oversize policy is refused there, by name. */ +const INCOMING_POLICY_READ_BOUND = 1024 * 1024 + 1; + +/** A sync whose local workflow ran but whose output was refused: mark a JSON result failed too. */ +function refusedSync(local: ExecutionResult, reason: string): ExecutionResult { + let stdout = local.stdout; + try { + const result = JSON.parse(stdout); + if (result && typeof result === "object" && result.run && typeof result.run === "object") { + result.run.status = "failed"; + result.run.reason = reason; + result.run.report = `${reason}\n${typeof result.run.report === "string" ? result.run.report : ""}`; + stdout = JSON.stringify(result); + } + } catch { /* Human-mode output keeps its report; stderr carries the reason. */ } + return { stdout, stderr: reason, exitCode: 1 }; +} + +/** What a refused tier A sync output says, and does, next (#4256). */ +async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintenanceOutputError, policy: { onPolicyChange?: (change: IncomingPolicyChange) => void; upstream?: string | null }): Promise { + if (error.paths.length === 1 && error.paths[0] === GOVERNANCE_POLICY_PATH) { + const content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); + if (content && policy.onPolicyChange) { + policy.onPolicyChange({ content, upstream: policy.upstream ?? null }); + return refusedSync(local, `Sync paused before publishing anything: the pull changes ${GOVERNANCE_POLICY_PATH}. Review the policy change; approving it adopts the policy, and the next sync completes.`); + } + if (content) return refusedSync(local, `Sync stopped before publishing anything: the pull changes ${GOVERNANCE_POLICY_PATH}, and a policy change needs the owner's review. Run Sync in the app to review it.`); + } + const policies = error.paths.some(path => isWithin("context/policies", path)); + return refusedSync(local, `${error.message}. Nothing was published. A sync never adopts this change: revert the upstream commit that makes it${policies ? `, then change the policy in chat (propose_policy_change)` : ""}.`); +} + +async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal; timeoutMs?: number; onPolicyChange?: (change: IncomingPolicyChange) => void; upstream?: string | null }, nativeManager: Parameters[1] | undefined, folderPaths?: readonly string[], log?: import("@opentelemetry/api-logs").Logger): Promise { if (!nativeManager) throw new Error("Local sync requires the configured native managed-storage manager; full-copy fallback is unavailable."); const view = await prepareNativeWorkerStartupView(command.brainPath, nativeManager, command.signal); let outputs: Awaited> | undefined; @@ -141,8 +180,15 @@ async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal command.signal?.throwIfAborted(); outputs = await prepareMaintenanceOutput(command.brainPath, { startupView: view, folderPaths, signal: command.signal }); const git = await prepareMaintenanceGit(command, outputs, command.signal, log); - const result = await runMaintenanceWorker({ ...command, tempKind: "sync", startupView: outputs.view, output: outputs.output, ...(git ? { git } : {}) }); - if (!result.killed) await outputs.publish(); + const { onPolicyChange, upstream, ...worker } = command; + const result = await runMaintenanceWorker({ ...worker, tempKind: "sync", startupView: outputs.view, output: outputs.output, ...(git ? { git } : {}) }); + if (!result.killed) { + try { await outputs.publish(); } + catch (error) { + if (!(error instanceof ProtectedMaintenanceOutputError) || result.exitCode !== 0) throw error; + return await protectedRefusal(result, error, { onPolicyChange, upstream }); + } + } return result; } finally { try { await outputs?.cleanup(); } finally { await view.cleanup(); } } } @@ -150,7 +196,9 @@ async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal /** Full deterministic sync with the same local merge behavior; remote races repeat its existing re-pull flow. */ export async function runMirrorSync(input: { log?: import("@opentelemetry/api-logs").Logger; folderPaths?: readonly string[]; nativeManager?: Parameters[1]; command: MaintenanceCommand; mirror: string; transportEnv?: MaintenanceCommand["env"]; signal?: AbortSignal; timeoutMs?: number; /** Called once the sync's first worker is about to start: after the mirror lock, the startup view and the origin probe (#4257). */ - onExecute?: () => void }): Promise { + onExecute?: () => void; + /** Called, before the sync ends, when its pull changes only the governance policy (#4256). Absent: the sync refuses and names the waiting change. */ + onPolicyChange?: (change: IncomingPolicyChange) => void }): Promise { // Standalone embedders have no attached database gate. Their private // mirror still serializes every local/transport phase in this process. return mirrorLocks.withLock(input.mirror, () => executeMirrorSync(input), { signal: input.signal }); @@ -166,7 +214,7 @@ async function executeMirrorSync(input: Parameters[0]): Pr finally { await originView.cleanup(); } input.signal?.throwIfAborted(); input.onExecute?.(); - if (remote === null) return runLocalSync({ ...command, credentials: false, + if (remote === null) return runLocalSync({ ...command, credentials: false, ...(input.onPolicyChange ? { onPolicyChange: input.onPolicyChange } : {}), ...(input.signal ? { signal: input.signal } : {}), ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}) }, input.nativeManager, input.folderPaths, input.log); prepareMirror(mirror, brain); const transport = async (args: readonly string[]) => { @@ -183,7 +231,8 @@ async function executeMirrorSync(input: Parameters[0]): Pr // Entire config/commit/pull/merge/judgment/index flow stays in a worker // with no credential. Only objects and refs are writable in the mirror; // config, HEAD, hooks and the directory itself remain read-only. - last = await runLocalSync({ ...command, credentials: false, + last = await runLocalSync({ ...command, credentials: false, upstream: mirrorHead(mirror), + ...(input.onPolicyChange ? { onPolicyChange: input.onPolicyChange } : {}), readPaths: [...(command.readPaths ?? []), mirror], writeDirectories: [join(mirror, "objects"), join(mirror, "refs")], gitConfig: [["safe.directory", brain], ["safe.directory", mirror], [`url.file://${mirror}.insteadOf`, remote], ["remote.origin.pushurl", `file://${mirror}`]], @@ -202,6 +251,19 @@ async function executeMirrorSync(input: Parameters[0]): Pr return last; } +/** The fetched upstream `main` in the mirror, or null when it cannot be read. */ +function mirrorHead(mirror: string): string | null { + const sha = /^[0-9a-f]{40}(?:[0-9a-f]{24})?$/; + try { const loose = readFileSync(join(mirror, "refs/heads/main"), "utf8").trim(); if (sha.test(loose)) return loose; } catch { /* packed */ } + try { + for (const line of readFileSync(join(mirror, "packed-refs"), "utf8").split("\n")) { + const [id, ref] = line.trim().split(" "); + if (ref === "refs/heads/main" && id && sha.test(id)) return id; + } + } catch { /* none */ } + return null; +} + /** A local mirror push is not a successful external push; keep hosted status and exit evidence consistent. */ function transportFailure(local: ExecutionResult, failed: ExecutionResult): ExecutionResult { const reason = `host Git transport failed: ${failed.stderr.trim() || failed.stdout.trim() || `exit ${failed.exitCode}`}`; diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index c1bb92f760..45dc2a1faa 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -16,6 +16,9 @@ import { requireJson } from "../middleware/origin.js"; import type { AppEnv } from "../app-env.js"; import type { AwaitableActivityStore } from "../activity/store.js"; import { observeWrite } from "../activity/store-writes.js"; +import { GOVERNANCE_POLICY_PATH } from "@schlessera/brain-common/internal/governance-policy"; +import { OwnerPolicyReviewError, type OwnerPolicyProposal, type OwnerPolicyReviews } from "../brain/owner-policy-reviews.js"; +import type { IncomingPolicyChange } from "../brain/sync-mirror.js"; /** * How long a UI sync may take from admission until its process has started @@ -43,6 +46,11 @@ interface BrainRoutesDeps { syncOutputGraceMs?: number; /** Where each UI sync records its run (#4257), as scheduled syncs do. Fail-open. */ activity?: AwaitableActivityStore; + /** + * Host-owned reviews of a policy change a sync's pull brings in (#4256). + * Absent: such a sync fails, naming the waiting change. + */ + policyReviews?: OwnerPolicyReviews; brainCliMinimum?: string; log?: Logger; brain: BrainClient; @@ -135,6 +143,20 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { }; } + /** Open the owner's review of an incoming policy change; never writes. */ + async function openPolicyReview(principalId: string, change: IncomingPolicyChange) { + let text: string; + try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(change.content); } + catch { return { ok: false as const, message: `The incoming ${GOVERNANCE_POLICY_PATH} is not UTF-8 text, so it cannot be reviewed. Revert the upstream commit that changes it.` }; } + const rationale = `Incoming from the brain's remote${change.upstream ? ` at commit ${change.upstream.slice(0, 12)}` : ""}: the pull changes ${GOVERNANCE_POLICY_PATH}. Approving adopts it, and the next sync completes.`; + try { + return { ok: true as const, proposal: await deps.policyReviews!.propose(principalId, () => text, undefined, rationale, + `The incoming policy did not validate, so nothing was proposed. Revert the upstream commit that changes ${GOVERNANCE_POLICY_PATH}, or fix it there`) }; + } catch (error) { + return { ok: false as const, message: error instanceof Error ? error.message : "The incoming policy change could not be reviewed." }; + } + } + return new Hono() .get("/brain/search", async (c) => { const q = c.req.query("q"); @@ -234,8 +256,8 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { text?: string; success?: boolean; reason?: string; - }) => { - if (data.type === "progress" && data.text) output = (output + data.text + "\n").slice(-SYNC_OUTPUT_TAIL_CHARS); + } | ({ type: "policy_review" } & OwnerPolicyProposal)) => { + if (data.type === "progress" && "text" in data && data.text) output = (output + data.text + "\n").slice(-SYNC_OUTPUT_TAIL_CHARS); return disconnected ? Promise.resolve() : stream.writeSSE({ data: JSON.stringify(data) }) .catch(() => { disconnected = true; }); }; @@ -259,6 +281,7 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { // Everything before the process starts is bounded (#4257): a probe or // launch that never settles must not hold the brain until a restart. const launching = new AbortController(); + let incoming: IncomingPolicyChange | undefined; let markStarted!: () => void; const started = new Promise(resolve => { markStarted = resolve; }); let timedOut = false; @@ -290,6 +313,7 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { sync: true, signal: launching.signal, onExecute: () => markStarted(), + ...(deps.policyReviews ? { onPolicyChange: (change: IncomingPolicyChange) => { incoming = change; } } : {}), }); launched = proc; // A launch that settles after its bound was already refused: stop it. @@ -364,6 +388,20 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { failure = `Sync failed (exit ${exitCode})${tail ? `: ${tail}` : ""}`; } + // The pull changes the governance policy (#4256): nothing was + // published. The owner who started this sync reviews the change. + const principalId = c.get("principal")?.id; + if (exitCode !== 0 && incoming && deps.policyReviews && principalId) { + const opened = await openPolicyReview(principalId, incoming); + if (opened.ok) { + await send({ type: "policy_review", ...opened.proposal }); + await send({ type: "done", success: false, reason: "policy_review", + text: "Sync paused: the pull changes the governance policy. Review it; after you approve, sync again." }); + return; + } + await send({ type: "progress", text: opened.message }); + } + await send({ type: "done", success: exitCode === 0, @@ -382,6 +420,25 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { }); }) + // The owner's answer to a sync's incoming policy review (#4256). + .post("/brain/sync/policy/:turnId/:requestId", requireJson(), async (c) => { + if (!deps.policyReviews) return c.json({ error: "Policy reviews are not available on this server." }, 404); + const principal = c.get("principal"); + if (!principal) return c.json({ error: "A signed-in owner answers a policy review." }, 403); + const { turnId, requestId } = c.req.param(); + if (turnId.length > 200 || requestId.length > 200) return c.json({ error: "Invalid request identity." }, 400); + const result = await readJsonBody(c).catch(() => null); + if (result instanceof Response) return result; + const body = result as { approve?: unknown } | null; + if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).some(key => key !== "approve") || typeof body.approve !== "boolean") + return c.json({ error: "Expected { approve } answering this review." }, 400); + try { return c.json(await deps.policyReviews.decide(principal.id, turnId, requestId, body.approve)); } + catch (error) { + if (error instanceof OwnerPolicyReviewError) return c.json({ error: error.message, code: error.code }, error.status); + throw error; + } + }) + // Recovery after a successful capture whose indexing failed. Coalesce // concurrent retries and never submit the captured content a second time. .post("/brain/index", requireJson(), async (c) => { diff --git a/packages/ui-server/tests/sync-policy-review.test.ts b/packages/ui-server/tests/sync-policy-review.test.ts new file mode 100644 index 0000000000..e26908b9cb --- /dev/null +++ b/packages/ui-server/tests/sync-policy-review.test.ts @@ -0,0 +1,164 @@ +/** + * A sync whose pull changes the governance policy opens a host-owned review + * instead of failing (#4256). The route publishes nothing itself: the review + * goes through the real policy writer, and only the owner's approval writes. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { Hono } from "hono"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { parseGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import type { AppEnv } from "../src/app-env.js"; +import type { Principal } from "../src/db/principals.js"; +import { createUiDb } from "../src/db/client.js"; +import { createPolicyProposals } from "../src/brain/policy-proposal.js"; +import { createOwnerPolicyReviews, OwnerPolicyReviewError, type OwnerPolicyJournal } from "../src/brain/owner-policy-reviews.js"; +import { createBrainRoutes } from "../src/routes/brain"; +import type { BrainClient } from "../src/brain/client"; +import type { HostBoundary, StreamingExecution } from "../src/brain/host-boundary"; +import type { KeytermSettings } from "../src/voice/keyterm-builder"; + +const CURRENT = `--- +schema_version: 1 +# Odysseus keeps outward writes closed. +--- +Odysseus decides what leaves Ithaca. +`; +const INCOMING = `--- +schema_version: 1 +# Odysseus keeps outward writes closed. +outward: + github: + repositories: [ithaca/*] +--- +Odysseus decides what leaves Ithaca. +`; +const UPSTREAM = "4b1d0c0ffee4b1d0c0ffee4b1d0c0ffee4b1d0c0"; +const owner = { id: "p-penelope", kind: "owner" } as Principal; +const suitor = { id: "p-antinous", kind: "owner" } as Principal; + +const cleanup: (() => void)[] = []; +afterEach(() => { for (const step of cleanup.splice(0).reverse()) step(); }); + +function brain() { + const root = mkdtempSync(join(tmpdir(), "odysseus-sync-policy-")); + cleanup.push(() => rmSync(root, { recursive: true, force: true })); + mkdirSync(join(root, "context/policies"), { recursive: true }); + writeFileSync(join(root, "context/policies/governance.md"), CURRENT); + return root; +} + +function failedProcess(): StreamingExecution { + const encoder = new TextEncoder(); + return { + stdout: new ReadableStream({ start(controller) { controller.enqueue(encoder.encode("Pulled 1 commit\n")); controller.close(); } }), + stderr: new ReadableStream({ start(controller) { controller.enqueue(encoder.encode("Sync paused before publishing anything\n")); controller.close(); } }), + exited: Promise.resolve(1), signalCode: null, kill() {}, + }; +} + +/** The real policy writer behind the sync's host-owned reviews, with a journal that admits a write only in a begun user window. */ +function setup(root: string, launch?: HostBoundary["launch"]) { + const db = createUiDb(":memory:"); cleanup.push(() => db.close()); + const active = new Set(), windows: string[] = []; + const journal: OwnerPolicyJournal = { + async begin(turnId, metadata) { expect(metadata.actor).toBe("user"); active.add(turnId); windows.push(turnId); }, + async finish(turnId) { active.delete(turnId); }, + }; + const events: unknown[] = []; + const proposals = createPolicyProposals({ root, db, lock: createKeyedLock(), + observeUserPolicy: (turnId, write) => { if (!active.has(turnId)) throw new Error("approved policy write requires an active user window"); write(); }, + recordEvent: review => { events.push(review); } }); + const reviews = createOwnerPolicyReviews({ root, proposals, journal, authorized: id => id === owner.id || id === suitor.id, + turnPrefix: "sync-policy", requestPrefix: "sync", fail: (status, code, message) => new OwnerPolicyReviewError(status, code, message) }); + cleanup.push(() => reviews.close()); + let launched = 0; + const routes = createBrainRoutes({ + brainPath: root, brain: { cliCommand: () => [process.execPath, "sync.ts"] } as BrainClient, + keyterms: { brainPath: root } as KeytermSettings, exec: {}, policyReviews: reviews, + boundary: { launch: launch ?? (async execution => { + launched++; + execution.onExecute?.(); + execution.onPolicyChange?.({ content: new TextEncoder().encode(INCOMING), upstream: UPSTREAM }); + return failedProcess(); + }) } as HostBoundary, + }); + const as = (principal: Principal) => new Hono().use("*", async (c, next) => { c.set("principal", principal); await next(); }).route("/api", routes); + return { as, windows, events, launched: () => launched }; +} + +const frames = async (response: Response) => (await response.text()).split("\n").filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6)) as Record); +const decide = (app: Hono, review: Record, approve: boolean) => app.request(`/api/brain/sync/policy/${review.turn_id}/${review.request_id}`, + { method: "POST", headers: { "Content-Type": "application/json", Origin: "http://localhost" }, body: JSON.stringify({ approve }) }); + +describe("a sync's incoming policy change (#4256)", () => { + test("streams a review of the exact incoming bytes and ends paused, writing nothing", async () => { + const root = brain(); + const { as } = setup(root); + const all = await frames(await as(owner).request("/api/brain/sync", { method: "POST" })); + const review = all.find(frame => frame.type === "policy_review"); + expect(review, "SYNC_STREAMS_POLICY_REVIEW").toBeDefined(); + expect(String(review!.turn_id)).toStartWith("sync-policy-"); + const shown = review!.review as { state: string; rationale: string; frontmatterDiff: string }; + expect(shown.state).toBe("pending"); + expect(shown.rationale).toContain(UPSTREAM.slice(0, 12)); + expect(shown.frontmatterDiff).toContain("+ outward:"); + expect(all.at(-1), "SYNC_ENDS_PAUSED").toMatchObject({ type: "done", success: false, reason: "policy_review" }); + expect(readFileSync(join(root, "context/policies/governance.md"), "utf8"), "NOTHING_WRITTEN_BEFORE_APPROVAL").toBe(CURRENT); + }); + + test("approval writes exactly the incoming bytes through the policy writer, in a user window", async () => { + const root = brain(); + const { as, windows, events } = setup(root); + const review = (await frames(await as(owner).request("/api/brain/sync", { method: "POST" }))).find(frame => frame.type === "policy_review")!; + const answered = await decide(as(owner), review, true); + expect(answered.status).toBe(200); + expect((await answered.json()).state, "APPROVED_REVIEW_WRITTEN").toBe("updated"); + expect(readFileSync(join(root, "context/policies/governance.md"), "utf8"), "INCOMING_BYTES_ADOPTED").toBe(INCOMING); + expect(windows).toEqual([review.turn_id]); + expect(events).toHaveLength(1); + const policy = parseGovernancePolicy(readFileSync(join(root, "context/policies/governance.md"))); + expect(policy.ok).toBe(true); + expect(policy.effective.outward.github.repositories, "NEXT_TURN_POLICY_ADMITS_REPOSITORY").toEqual(["ithaca/*"]); + }); + + test("declining writes nothing, and the next sync opens the review again", async () => { + const root = brain(); + const { as, launched } = setup(root); + const review = (await frames(await as(owner).request("/api/brain/sync", { method: "POST" }))).find(frame => frame.type === "policy_review")!; + expect((await (await decide(as(owner), review, false)).json()).state).toBe("declined"); + expect(readFileSync(join(root, "context/policies/governance.md"), "utf8"), "DECLINE_WRITES_NOTHING").toBe(CURRENT); + const again = await frames(await as(owner).request("/api/brain/sync", { method: "POST" })); + expect(again.some(frame => frame.type === "policy_review"), "NEXT_SYNC_REVIEWS_AGAIN").toBe(true); + expect(launched()).toBe(2); + }); + + test("another principal or an unknown review is refused, and nothing is written", async () => { + const root = brain(); + const { as } = setup(root); + const review = (await frames(await as(owner).request("/api/brain/sync", { method: "POST" }))).find(frame => frame.type === "policy_review")!; + const other = await decide(as(suitor), review, true); + expect(other.status, "OTHER_PRINCIPAL_REFUSED").toBe(404); + const unknown = await decide(as(owner), { turn_id: "sync-policy-unknown", request_id: "sync-unknown" }, true); + expect(unknown.status, "UNKNOWN_REVIEW_REFUSED").toBe(404); + const foreign = await decide(as(owner), { turn_id: "settings-apify-1", request_id: "apify-1" }, true); + expect(foreign.status, "FOREIGN_REVIEW_FAMILY_REFUSED").toBe(404); + expect(readFileSync(join(root, "context/policies/governance.md"), "utf8")).toBe(CURRENT); + }); + + test("an incoming policy that does not validate fails the sync with next steps and opens no review", async () => { + const root = brain(); + const { as } = setup(root, async execution => { + execution.onExecute?.(); + execution.onPolicyChange?.({ content: new TextEncoder().encode("---\nschema_version: 99\n---\n"), upstream: null }); + return failedProcess(); + }); + const all = await frames(await as(owner).request("/api/brain/sync", { method: "POST" })); + expect(all.some(frame => frame.type === "policy_review"), "INVALID_OPENS_NO_REVIEW").toBe(false); + expect(all.some(frame => frame.type === "progress" && String(frame.text).includes("Revert the upstream commit")), "INVALID_NAMES_NEXT_STEP").toBe(true); + expect(all.at(-1)).toMatchObject({ type: "done", success: false }); + expect(readFileSync(join(root, "context/policies/governance.md"), "utf8")).toBe(CURRENT); + }); +}); From de628cbcdd6e9d320d7249046e4971b3a51d026f Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:59:15 +0000 Subject: [PATCH 02/21] feat(ui-server, ui-react): review a sync's incoming policy change; docs, decision and tests (#4256) Co-Authored-By: Claude Opus 5.5 --- .changeset/4256-sync-policy-review.md | 7 ++ docs/decisions/governed-writable-workers.md | 18 +++++ docs/http-api.md | 26 ++++++- docs/integration-contract/http.md | 16 +++++ .../quick-actions/streaming-modal.tsx | 9 +++ .../quick-actions/sync-policy-review.tsx | 59 ++++++++++++++++ .../tests/render/slide-panel.test.tsx | 43 ++++++++++++ packages/ui-server/tests/sync-mirror.test.ts | 68 +++++++++++++++++++ .../tests/sync-policy-review.test.ts | 17 +++-- 9 files changed, 255 insertions(+), 8 deletions(-) create mode 100644 .changeset/4256-sync-policy-review.md create mode 100644 packages/ui-react/src/components/quick-actions/sync-policy-review.tsx diff --git a/.changeset/4256-sync-policy-review.md b/.changeset/4256-sync-policy-review.md new file mode 100644 index 0000000000..22dcbaa1b6 --- /dev/null +++ b/.changeset/4256-sync-policy-review.md @@ -0,0 +1,7 @@ +--- +"@schlessera/brain-ui-server": minor +"@schlessera/brain-ui-react": minor +"@schlessera/brain-ui-sdk": patch +--- + +A hosted sync whose pull changes `context/policies/governance.md` no longer fails every time until the upstream commit is reverted (#4256). It publishes nothing and opens a review of the incoming policy, which the owner approves or declines in the sync panel. Approving writes exactly the incoming bytes through the existing policy writer, and the next sync completes. Declining writes nothing. `POST /api/brain/sync` sends a new `policy_review` frame and ends with `reason: "policy_review"`, and `POST /api/brain/sync/policy/:turnId/:requestId` takes the owner's `{ approve }`. A scheduled sync opens no review and names the waiting change. Any other refused tier A change keeps its refusal, and the message now says to revert the upstream commit, or, for a policy file, to change the policy in chat. diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 08e7d87cc5..6693f1238e 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -836,6 +836,24 @@ Publication also refuses deletion of a tier A ancestor directory, including an empty `context` or `.git` whose protected descendants are currently absent. This host-side check applies before any changed output is installed; worker namespace mount points alone do not constrain the host publisher. + +> **2026-11-20 — An incoming policy change from a sync is reviewed by the owner +> ([#4256](https://github.com/schlessera/brain-kit/issues/4256), maintainer ruling option 1).** +> The policy file is versioned host input, so a pull is where a policy change +> arrives. The refusal above still holds: a hosted sync's worker output never +> publishes a tier A change. When the only refused path is +> `context/policies/governance.md`, the host reads the output's bytes before +> cleanup, publishes nothing, and opens a host-owned review of them through the +> existing policy proposals, the only policy writer, as Settings › Apify does +> (`createOwnerPolicyReviews`, `packages/ui-server/src/brain/owner-policy-reviews.ts`). +> Only the owner whose UI sync opened it can answer, and only an approval +> writes, in a `user` journal window. The next sync then merges the identical +> change cleanly. A scheduled sync opens no review and names the waiting change. +> Every other tier A change keeps its refusal, with next-step text. No agent +> runtime, worker or autonomous turn proposes or answers these reviews, and the +> rationale shown is fixed host text. A Settings control for +> `outward.github.repositories` was not taken: chat's `propose_policy_change` +> already edits it. Within one server process, maintenance clients serialize preparation through publication per canonical brain. Even readers produce SQLite projections or Git attribute objects in their private outputs; concurrent copies of that diff --git a/docs/http-api.md b/docs/http-api.md index 57ab56feb5..e2b1d9ed3d 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -10,7 +10,7 @@ compatibility guarantee. Authentication requirements are a separate property. A public liveness probe can be supported; an authenticated settings route can be internal. -The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review, safety-recording recovery, GitHub detail-page, live-persona and markup-upload and human trust Settings routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 195 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery, attachment-read, interactive HTML preview, saved-audio transcription, human-started hygiene-review, governance-event, roadblock-report, reference-grant, Apify-state, Apify-policy, retained-journal/user-revert, untrusted-mark, chat-deletion, individual safety-review, safety-recording recovery, GitHub detail-page, live-persona and markup-upload, human trust Settings and sync policy-review routes (whose `/api/settings/voice` also carries the live-service default) mounted by `createApp`: 196 unique declared method/path pairs, plus the conditional SPA fallback. It describes the current implementation, including limitations, rather than a proposed redesign. Unknown response fields must be tolerated. There is no HTTP API revision @@ -219,6 +219,7 @@ client code has a gap. Source owners are listed after the table. | POST | `/api/apify/account` | I | Confirm the token's changed Apify account | Settings UI (#3159); live human owners only. Starts a new authority generation; accepts no token. | | POST | `/api/apify/policy` | I | Propose one Apify setting through the policy-change review | Settings UI (#3163); live human owners only. `{ change, base_hash }` names exactly one of `enabled`, `discovery`, `actors` or `remove_grant` and the policy version it changes. Returns `{ turn_id, request_id, review }` with a pending `PolicyChangeReview` of the complete proposed `governance.md`; writes nothing. 409 when the policy changed since it was read; 422 when the file cannot be rewritten exactly. | | POST | `/api/apify/policy/:turnId/:requestId` | I | Answer that exact review | Settings UI (#3163); only the proposing owner. `{ approve }`; an approval lets the existing policy writer publish it inside a user journal window. A repeated or late answer returns the recorded receipt and never writes again; a lost answer is reconciled through `GET /api/policy-proposals/:turnId/:requestId`. | +| POST | `/api/brain/sync/policy/:turnId/:requestId` | I | Answer a sync's incoming policy review | Sync panel (#4256); only the owner whose sync opened it. `{ approve }`; an approval lets the existing policy writer publish the incoming bytes inside a user journal window, and the owner syncs again. A repeated or late answer returns the recorded receipt and never writes again; a review of another family is never read here. | | POST | `/share-target` | S | Explain missing service worker without reading body | SDK share-target and custom PWA shells; preserve ShareIntakeResult and body-unread fallback. | | GET | `/ws` | S | Authenticate and admit WebSocket upgrade | SDK BrainUiClient; supported HTTP upgrade boundary, followed by the existing wire contract. | | GET | `/*` (conditional) | I | Serve configured SPA deep links | Custom shell with `staticRoot`; deployment asset transport, not an independent JSON API. | @@ -228,7 +229,7 @@ Authentication factories live in [auth.ts](../packages/ui-server/src/middleware/ [passkeys.ts](../packages/ui-server/src/middleware/passkeys.ts) and [principals.ts](../packages/ui-server/src/middleware/principals.ts). [app.ts](../packages/ui-server/src/app.ts) owns prefixing and middleware order. -All 195 declared endpoints are mounted regardless of backend, renderer or +All 196 declared endpoints are mounted regardless of backend, renderer or speech-provider availability: unavailable capabilities return the responses below rather than removing their handlers. Only static serving is conditional. @@ -642,7 +643,26 @@ kind and origin `cron`, `jobName: "ui-sync"`, attributed to the requesting principal) whose terminal outcome carries the exit status and the last non-empty output lines, with the combined output tail as its `job_output` event, so a result survives a disconnected reader. A failure also logs -`ui sync failed` with the same text on the `brain` logger. Successful sync attempts voice keyterm rebuild; a rebuild failure +`ui sync failed` with the same text on the `brain` logger. + +**Incoming policy change (additive, #4256).** On a hosted install, a pull +whose only tier A change is `context/policies/governance.md` publishes +nothing. When the requesting principal is a current owner, the stream sends +`{ type: "policy_review", turn_id, request_id, review }`, where `review` is the +same `PolicyChangeReview` a chat policy card shows (base hash, frontmatter +diff, changed sections, body diff, and a fixed host rationale naming the +upstream commit), and ends with `{ type: "done", success: false, reason: +"policy_review", text }`. The owner answers it through +`POST /api/brain/sync/policy/:turnId/:requestId`. Approval writes exactly the +incoming bytes through the existing policy writer (journal actor `user`, class +`policy`, a `policy_change` governance event); the next admitted turn reads +it, and the next sync completes. Decline writes nothing, and the next sync +opens the review again. An incoming policy that is not UTF-8 or does not +validate opens no review: a progress line names the next step and the sync +fails. A scheduled sync opens no review; it fails naming the waiting change. +Any other refused tier A change keeps its refusal, and its text says to revert +the upstream commit (and, under `context/policies/`, to change the policy in +chat with `propose_policy_change`). Successful sync attempts voice keyterm rebuild; a rebuild failure is progress text and does not turn successful sync into failure. A degraded rebuild (no usable core peer, or an index core cannot read) is reported as progress text and not cached. A canonical diff --git a/docs/integration-contract/http.md b/docs/integration-contract/http.md index a27ea82c45..8b145790bf 100644 --- a/docs/integration-contract/http.md +++ b/docs/integration-contract/http.md @@ -271,6 +271,22 @@ Three additions ([HTTP reference](../http-api.md#corpus-queries-capture-and-sync terminal outcome carries the exit status and last output lines, and its `job_output` event carries the output tail. + + +### A sync's incoming policy change is reviewed, not failed (additive, #4256) + +`POST /api/brain/sync` may send one new frame, +`{ type: "policy_review", turn_id, request_id, review: PolicyChangeReview }`, +followed by `{ type: "done", success: false, reason: "policy_review", text }`, +when a hosted pull's only tier A change is `context/policies/governance.md` +([HTTP reference](../http-api.md#corpus-queries-capture-and-sync)). Nothing is +published. The internal `POST /api/brain/sync/policy/:turnId/:requestId` +takes `{ approve }` from the owner whose sync opened the review and returns the +recorded `PolicyChangeReview`; only an approval writes, through the existing +policy writer. `brainSync()` keeps mapping the terminal frame to +`{ success: false, message }`, and clients that ignore unknown frame types are +unaffected. No agent runtime proposes or answers these reviews. + ### Typed status software identity (additive, #598) diff --git a/packages/ui-react/src/components/quick-actions/streaming-modal.tsx b/packages/ui-react/src/components/quick-actions/streaming-modal.tsx index 93763d1c74..813bc5a0b4 100644 --- a/packages/ui-react/src/components/quick-actions/streaming-modal.tsx +++ b/packages/ui-react/src/components/quick-actions/streaming-modal.tsx @@ -3,6 +3,7 @@ import { useState, useEffect, useRef } from "react"; import { SlidePanel } from "../layout/slide-panel.js"; import { linkifyPaths } from "../chat/brain-markdown.js"; import { StreamingOutput, type StreamState } from "./streaming-output.js"; +import { isSyncPolicyReviewFrame, SyncPolicyReview, type SyncPolicyReviewFrame } from "./sync-policy-review.js"; /** * The container (S6) for a streamed backend job: the request, the SSE reader @@ -26,6 +27,8 @@ export function StreamingPanel({ const root = useBrainUiRoot(); const [state, setState] = useState("idle"); const [lines, setLines] = useState([]); + /** A sync's incoming policy review (#4256), shown below the log once the stream offers one. */ + const [policyReview, setPolicyReview] = useState(null); const scrollRef = useRef(null); const controllerRef = useRef(null); @@ -34,6 +37,7 @@ export function StreamingPanel({ setState("running"); setLines([]); + setPolicyReview(null); let disposed = false; let reader: ReadableStreamDefaultReader | undefined; @@ -85,6 +89,10 @@ export function StreamingPanel({ try { const data = JSON.parse(dataLine.slice(6)); + if (isSyncPolicyReviewFrame(data)) { + setPolicyReview({ turn_id: data.turn_id, request_id: data.request_id, review: data.review }); + continue; + } if (data.text !== undefined) { setLines((l) => [...l, data.text]); } @@ -150,6 +158,7 @@ export function StreamingPanel({ }} onClose={onClose} /> + {policyReview && } ); } diff --git a/packages/ui-react/src/components/quick-actions/sync-policy-review.tsx b/packages/ui-react/src/components/quick-actions/sync-policy-review.tsx new file mode 100644 index 0000000000..5cd69d9e9f --- /dev/null +++ b/packages/ui-react/src/components/quick-actions/sync-policy-review.tsx @@ -0,0 +1,59 @@ +import { useRef, useState } from "react"; +import { ApprovalCard, Callout, DiffBlock, Disclosure } from "@schlessera/brain-ui-kit"; +import type { PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; +import { useBrainUiRoot } from "../../root-context.js"; + +/** A sync's `policy_review` frame (#4256): the host-owned review of an incoming policy change. */ +export interface SyncPolicyReviewFrame { turn_id: string; request_id: string; review: PolicyChangeReview } + +export function isSyncPolicyReviewFrame(value: unknown): value is SyncPolicyReviewFrame & { type: "policy_review" } { + const frame = value as Partial & { type?: unknown }; + return !!frame && frame.type === "policy_review" && typeof frame.turn_id === "string" && typeof frame.request_id === "string" + && !!frame.review && typeof frame.review === "object" && typeof frame.review.state === "string"; +} + +/** + * The owner's review of a policy change a sync's pull brought in, with the + * same exact-diff presentation as a chat policy card. Nothing was published; + * only Approve writes, through the host's policy writer, and the owner syncs + * again afterwards. The answer is sent once and never repeated. + */ +export function SyncPolicyReview({ frame }: { frame: SyncPolicyReviewFrame }) { + const root = useBrainUiRoot(); + const [review, setReview] = useState(frame.review); + const [busy, setBusy] = useState(false), [error, setError] = useState(""); + const sent = useRef(false), receipt = useRef(null); + async function decide(approve: boolean) { + if (sent.current || busy || review.state !== "pending") return; + sent.current = true; setBusy(true); setError(""); + try { + const response = await root.request(root.backendUrl(`/api/brain/sync/policy/${encodeURIComponent(frame.turn_id)}/${encodeURIComponent(frame.request_id)}`), { + method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ approve }), + }); + const body = await response.json().catch(() => null) as (PolicyChangeReview & { error?: string }) | null; + if (!response.ok || !body || typeof body.state !== "string") throw new Error(body?.error ?? `HTTP ${response.status}`); + setReview(body); + } catch (cause) { + setError(`The host did not confirm this answer (${cause instanceof Error ? cause.message : "unknown error"}). Sync again to see the review's state.`); + } finally { setBusy(false); queueMicrotask(() => receipt.current?.focus({ preventScroll: true })); } + } + const pending = review.state === "pending" && !busy && !sent.current; + return
+ {pending ?
+ void decide(true)} onDeny={() => void decide(false)}> +

From the sync

{review.rationale}
+

Exact base: {review.baseHash ?? "no policy file"}

+

Changed sections: {review.sections.length ? review.sections.join(", ") : "frontmatter values unchanged"}.

+
{review.frontmatterDiff ? :

Frontmatter bytes unchanged.

}
+

{review.bodyChanged ? "Body text changed." : "Body text unchanged."}

+ {review.bodyChanged &&
} + {review.warnings.map(warning => )} +
+ Incoming policy change. Review before approving. +
:
+

{busy ? "Sending your answer…" : error || review.message}

+ {review.state === "updated" && !error &&

The policy is adopted. Sync again to finish the sync.

} +
} +
; +} diff --git a/packages/ui-react/tests/render/slide-panel.test.tsx b/packages/ui-react/tests/render/slide-panel.test.tsx index cb22ea8d2b..2c571a58c2 100644 --- a/packages/ui-react/tests/render/slide-panel.test.tsx +++ b/packages/ui-react/tests/render/slide-panel.test.tsx @@ -399,3 +399,46 @@ describe("WhatsupPanel reads the briefing endpoint", () => { } finally { view.unmount(); root.dispose(); } }); }); + +describe("StreamingPanel sync policy review (#4256)", () => { + const review = { + turnId: "sync-policy-ithaca", requestId: "sync-harbor", state: "pending", path: "context/policies/governance.md", + baseHash: null, proposedHash: "b".repeat(64), frontmatterDiff: "+ outward:\n+ github:\n+ repositories: [ithaca/*]", + sections: ["outward"], bodyChanged: false, bodyDiff: "", rationale: "Incoming from the brain's remote at commit 4b1d0c0ffee4: the pull changes context/policies/governance.md.", + warnings: [], message: "Review the incoming policy change.", + }; + test("renders the incoming review below the log and sends the owner's one answer to its decide route", async () => { + const { root, requests } = transport(); + const view = render( + + {}} /> + + ); + try { + const frames = [ + { type: "progress", text: "Pulled 1 commit" }, + { type: "policy_review", turn_id: review.turnId, request_id: review.requestId, review }, + { type: "done", success: false, reason: "policy_review", text: "Sync paused: the pull changes the governance policy." }, + ].map(frame => `data: ${JSON.stringify(frame)}\n\n`).join(""); + await act(async () => { requests[0]!.response.resolve(new Response(frames)); await flushPromises(); }); + expect(view.getByText("Sync paused: the pull changes the governance policy.")).toBeTruthy(); + const card = view.baseElement.querySelector("[data-sync-policy-review]"); + expect(card?.getAttribute("data-policy-state"), "SYNC_REVIEW_RENDERED").toBe("pending"); + expect(card?.textContent).toContain("4b1d0c0ffee4"); + expect(card?.textContent).toContain("repositories: [ithaca/*]"); + fireEvent.click(view.getByRole("button", { name: "Approve and write" })); + await flushPromises(); + expect(requests[1]?.url, "SYNC_REVIEW_DECIDE_ROUTE").toBe("https://sync.example/api/brain/sync/policy/sync-policy-ithaca/sync-harbor"); + expect(requests[1]?.init?.method).toBe("POST"); + expect(JSON.parse(String(requests[1]?.init?.body)), "SYNC_REVIEW_APPROVE_BODY").toEqual({ approve: true }); + await act(async () => { + requests[1]!.response.resolve(Response.json({ ...review, state: "updated", message: "Policy updated." })); + await flushPromises(); await flushPromises(); + }); + expect(view.baseElement.querySelector("[data-sync-policy-review]")?.getAttribute("data-policy-state")).toBe("updated"); + expect(view.getByText("The policy is adopted. Sync again to finish the sync.")).toBeTruthy(); + expect(view.queryByRole("button", { name: "Approve and write" }), "SYNC_REVIEW_ANSWERED_ONCE").toBeNull(); + expect(requests).toHaveLength(2); + } finally { view.unmount(); root.dispose(); } + }); +}); diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index a2ab5c81c2..ed5c65cba8 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -126,6 +126,74 @@ test("full hosted sync commits, pulls and pushes while config and included filte } finally { server.stop(true); if (old === undefined) delete process.env.BRAIN_UI_SYNC_GITHUB_TOKEN; else process.env.BRAIN_UI_SYNC_GITHUB_TOKEN = old; } }, 120_000); +test("an upstream governance policy commit pauses a hosted sync for review, and an adopted policy lets the next sync complete (#4256)", async () => { + const f = fixture(); + const boundary = createHostBoundary({ brainPath: f.brain, nativeManager: f.nativeManager, dbPath: f.dbPath }); + const server = fixtureRemote(f.root, f.remote); + git(f.brain, "remote", "set-url", "origin", `${server.url}remote.git`); + const policy = "---\nschema_version: 1\noutward:\n github:\n repositories: [ithaca/*]\n---\nOdysseus decides what leaves Ithaca.\n"; + const other = join(f.root, "other"); + git(other, "pull", "--quiet", "origin", "main"); + mkdirSync(join(other, "context/policies"), { recursive: true }); + writeFileSync(join(other, "context/policies/governance.md"), policy); + git(other, "add", "."); git(other, "commit", "-m", "Open GitHub writes to Ithaca"); git(other, "push", "origin", "main"); + const upstream = git(f.remote, "rev-parse", "main"); + try { + const client = createBrainClient({ brainPath: f.brain, boundary, exec: {} }); + // A scheduled sync has no owner to review: it refuses and names the waiting change. + const scheduled = await client.sync().then(() => null, (error: BrainSyncError) => error); + expect(scheduled, "SCHEDULED_SYNC_REFUSED").toBeInstanceOf(BrainSyncError); + expect(`${scheduled!.message}\n${JSON.stringify(scheduled!.result)}`, "SCHEDULED_NAMES_WAITING_REVIEW").toContain("needs the owner's review"); + expect(existsSync(join(f.brain, "context/policies/governance.md")), "SCHEDULED_PUBLISHED_NOTHING").toBe(false); + + // A UI sync hands the incoming bytes to the host and publishes nothing. + const changes: { content: Uint8Array; upstream: string | null }[] = []; + const proc = await boundary.launch({ argv: [join(f.brain, "node_modules/.bin/brain"), "sync", "--human"], env: { PATH: process.env.PATH }, + credentials: false, gate: "exclusive", sync: true, purpose: "policy review sync", onPolicyChange: change => { changes.push(change); } }); + void new Response(proc.stdout).text().catch(() => {}); + const stderr = new Response(proc.stderr).text(); + expect(await proc.exited, "UI_SYNC_PAUSED_EXIT").toBe(1); + expect(await stderr, "UI_SYNC_PAUSED_TEXT").toContain("Sync paused before publishing anything"); + expect(changes, "UI_SYNC_HANDS_OVER_CHANGE").toHaveLength(1); + expect(new TextDecoder().decode(changes[0]!.content), "INCOMING_BYTES_EXACT").toBe(policy); + expect(changes[0]!.upstream, "INCOMING_NAMES_UPSTREAM").toBe(upstream); + expect(existsSync(join(f.brain, "context/policies/governance.md")), "UI_PUBLISHED_NOTHING").toBe(false); + expect(existsSync(join(f.brain, "notes/sea.md")), "UI_PUBLISHED_NO_OTHER_FILE").toBe(false); + + // What an approved review writes, through the policy writer, then the next sync completes. + mkdirSync(join(f.brain, "context/policies"), { recursive: true }); + writeFileSync(join(f.brain, "context/policies/governance.md"), policy); + const result = await client.sync().catch(error => { throw new Error(JSON.stringify(error.result) + "\n" + error.message); }); + expect(result.result?.run.status, "ADOPTED_SYNC_COMPLETES").toBe("complete"); + expect(readFileSync(join(f.brain, "context/policies/governance.md"), "utf8")).toBe(policy); + expect(readFileSync(join(f.brain, "notes/sea.md"), "utf8")).toContain("Telemachus watches the tide."); + } finally { server.stop(true); } +}, 180_000); + +test("an upstream change to another tier A input keeps its refusal and says what to do next (#4256)", async () => { + const f = fixture(); + const boundary = createHostBoundary({ brainPath: f.brain, nativeManager: f.nativeManager, dbPath: f.dbPath }); + const server = fixtureRemote(f.root, f.remote); + git(f.brain, "remote", "set-url", "origin", `${server.url}remote.git`); + const other = join(f.root, "other"); + git(other, "pull", "--quiet", "origin", "main"); + writeFileSync(join(other, "bunfig.toml"), "[install]\nexact = true\n"); + git(other, "add", "."); git(other, "commit", "-m", "Pin installs"); git(other, "push", "origin", "main"); + try { + const changes: unknown[] = []; + const proc = await boundary.launch({ argv: [join(f.brain, "node_modules/.bin/brain"), "sync", "--human"], env: { PATH: process.env.PATH }, + credentials: false, gate: "exclusive", sync: true, purpose: "tier A refusal sync", onPolicyChange: change => { changes.push(change); } }); + void new Response(proc.stdout).text().catch(() => {}); + const stderr = new Response(proc.stderr).text(); + expect(await proc.exited).toBe(1); + const text = await stderr; + expect(text, "TIER_A_REFUSED").toContain("maintenance output cannot change protected input bunfig.toml"); + expect(text, "TIER_A_NEXT_STEP").toContain("revert the upstream commit"); + expect(changes, "TIER_A_NOT_REVIEWABLE").toEqual([]); + expect(existsSync(join(f.brain, "bunfig.toml"))).toBe(false); + } finally { server.stop(true); } +}, 180_000); + test("hosted sync retains startup imports while publishing outputs beside a newer governed edit", async () => { const f = fixture(); const boundary = createHostBoundary({ brainPath: f.brain, nativeManager: f.nativeManager, dbPath: f.dbPath }); diff --git a/packages/ui-server/tests/sync-policy-review.test.ts b/packages/ui-server/tests/sync-policy-review.test.ts index e26908b9cb..9ff4b27165 100644 --- a/packages/ui-server/tests/sync-policy-review.test.ts +++ b/packages/ui-server/tests/sync-policy-review.test.ts @@ -86,11 +86,13 @@ function setup(root: string, launch?: HostBoundary["launch"]) { }) } as HostBoundary, }); const as = (principal: Principal) => new Hono().use("*", async (c, next) => { c.set("principal", principal); await next(); }).route("/api", routes); - return { as, windows, events, launched: () => launched }; + const family = (turnPrefix: string, requestPrefix: string) => createOwnerPolicyReviews({ root, proposals, journal, authorized: () => true, + turnPrefix, requestPrefix, fail: (status, code, message) => new OwnerPolicyReviewError(status, code, message) }); + return { as, windows, events, launched: () => launched, family }; } const frames = async (response: Response) => (await response.text()).split("\n").filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6)) as Record); -const decide = (app: Hono, review: Record, approve: boolean) => app.request(`/api/brain/sync/policy/${review.turn_id}/${review.request_id}`, +const decide = (app: Hono, review: { turn_id?: unknown; request_id?: unknown }, approve: boolean) => app.request(`/api/brain/sync/policy/${review.turn_id}/${review.request_id}`, { method: "POST", headers: { "Content-Type": "application/json", Origin: "http://localhost" }, body: JSON.stringify({ approve }) }); describe("a sync's incoming policy change (#4256)", () => { @@ -117,7 +119,7 @@ describe("a sync's incoming policy change (#4256)", () => { expect(answered.status).toBe(200); expect((await answered.json()).state, "APPROVED_REVIEW_WRITTEN").toBe("updated"); expect(readFileSync(join(root, "context/policies/governance.md"), "utf8"), "INCOMING_BYTES_ADOPTED").toBe(INCOMING); - expect(windows).toEqual([review.turn_id]); + expect(windows).toEqual([String(review.turn_id)]); expect(events).toHaveLength(1); const policy = parseGovernancePolicy(readFileSync(join(root, "context/policies/governance.md"))); expect(policy.ok).toBe(true); @@ -137,13 +139,18 @@ describe("a sync's incoming policy change (#4256)", () => { test("another principal or an unknown review is refused, and nothing is written", async () => { const root = brain(); - const { as } = setup(root); + const { as, family } = setup(root); const review = (await frames(await as(owner).request("/api/brain/sync", { method: "POST" }))).find(frame => frame.type === "policy_review")!; const other = await decide(as(suitor), review, true); expect(other.status, "OTHER_PRINCIPAL_REFUSED").toBe(404); const unknown = await decide(as(owner), { turn_id: "sync-policy-unknown", request_id: "sync-unknown" }, true); expect(unknown.status, "UNKNOWN_REVIEW_REFUSED").toBe(404); - const foreign = await decide(as(owner), { turn_id: "settings-apify-1", request_id: "apify-1" }, true); + // A recorded review of another family (Settings) is never read or answered through the sync route. + const settings = family("settings-apify", "apify"); + cleanup.push(() => settings.close()); + const opened = await settings.propose(owner.id, () => INCOMING, undefined, "Settings change", "invalid"); + await settings.decide(owner.id, opened.turn_id, opened.request_id, false); + const foreign = await decide(as(owner), opened, true); expect(foreign.status, "FOREIGN_REVIEW_FAMILY_REFUSED").toBe(404); expect(readFileSync(join(root, "context/policies/governance.md"), "utf8")).toBe(CURRENT); }); From 2a991ee57639dc685770921155d0f5ce89a552af Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:17:59 +0000 Subject: [PATCH 03/21] fix(ui-server): keep the owner review helpers module-private (#4256) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/owner-policy-reviews.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/ui-server/src/brain/owner-policy-reviews.ts b/packages/ui-server/src/brain/owner-policy-reviews.ts index 1be98db410..356a51fe95 100644 --- a/packages/ui-server/src/brain/owner-policy-reviews.ts +++ b/packages/ui-server/src/brain/owner-policy-reviews.ts @@ -25,7 +25,7 @@ export interface OwnerPolicyJournal { /** A review the owner can decide: its identity and the review as first shown. */ export interface OwnerPolicyProposal { turn_id: string; request_id: string; review: PolicyChangeReview } -export type OwnerPolicyRefusal = "not_authorized" | "busy" | "stale" | "policy_invalid" | "not_found"; +type OwnerPolicyRefusal = "not_authorized" | "busy" | "stale" | "policy_invalid" | "not_found"; /** A refused review request, with its HTTP status and a fixed message; it never carries policy text. */ export class OwnerPolicyReviewError extends Error { @@ -35,7 +35,7 @@ export class OwnerPolicyReviewError extends Error { } } -export interface OwnerPolicyReviewOptions { +interface OwnerPolicyReviewOptions { root: string; proposals: PolicyProposals; journal: OwnerPolicyJournal; @@ -53,12 +53,12 @@ export interface OwnerPolicyReviewOptions { /** At most this many unanswered reviews per owner, per review family. */ const MAX_PENDING = 4; -export function readGovernancePolicy(root: string): string | null { +function readGovernancePolicy(root: string): string | null { try { return readFileSync(join(root, GOVERNANCE_POLICY_PATH), "utf8"); } catch (error) { if ((error as NodeJS.ErrnoException).code === "ENOENT") return null; throw error; } } -export const policyHash = (text: string | null) => text === null ? null : createHash("sha256").update(text, "utf8").digest("hex"); +const policyHash = (text: string | null) => text === null ? null : createHash("sha256").update(text, "utf8").digest("hex"); export function createOwnerPolicyReviews(options: OwnerPolicyReviewOptions) { const timeoutMs = options.timeoutMs ?? 10 * 60_000; From 6956cf5823d13643d872190eb105467053f982f0 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:18:41 +0000 Subject: [PATCH 04/21] fix(ui-server): drop an unused Apify settings import (#4256) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/apify/settings.ts | 1 - 1 file changed, 1 deletion(-) diff --git a/packages/ui-server/src/apify/settings.ts b/packages/ui-server/src/apify/settings.ts index d617a99fd0..a892181ae0 100644 --- a/packages/ui-server/src/apify/settings.ts +++ b/packages/ui-server/src/apify/settings.ts @@ -19,7 +19,6 @@ import { existsSync } from "node:fs"; import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; import { checkGovernancePolicy, GOVERNANCE_POLICY_PATH } from "@schlessera/brain-common/internal/governance-policy"; import { liability, type ApifyLedger, type ApifyRuns, type ApifyStatus, type ApifyCoverageScope } from "@schlessera/brain-common/internal/apify"; -import type { PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; import type { ApifyGrantRead, ApifyPolicyChange, ApifyPolicyMode, ApifyPolicyProposalRead, ApifyPolicyRead, ApifySettingsRead, ApifySpendRead, ApifySpendScopeRead, ApifyUnresolvedRunRead, From 426177a545398cf0011f19d152bd34c6b1c4c75c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 14:20:29 +0000 Subject: [PATCH 05/21] chore(ui-sdk): record ProtectedMaintenanceOutputError in the API report (#4256) Co-Authored-By: Claude Opus 5.5 --- api-report/ui-sdk.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/api-report/ui-sdk.txt b/api-report/ui-sdk.txt index a993b8e283..c2fe88e0bb 100644 --- a/api-report/ui-sdk.txt +++ b/api-report/ui-sdk.txt @@ -1425,6 +1425,7 @@ export "./internal" (./src/internal.ts) PROVIDER_RELAY_KEYS_NAME PROVIDER_RELAY_SOCKET_NAME type PreparedWorkerOutput + ProtectedMaintenanceOutputError type ProviderRelay type ProviderRelayOptions type ProviderRelayReceipt From f3320cf09fe13077007274a8c295b173915fd6a9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 15:02:30 +0000 Subject: [PATCH 06/21] fix(ui-server): review only an upstream policy blob, a first policy too; a paused sync is not a failure (#4256) The incoming bytes must equal the upstream commit's policy blob, read by the host transport, so worker output is never a policy source; a sync without a remote reviews nothing. A first policy, whose pull also creates context/policies, is reviewable. A paused UI sync's Activity run ends as cancelled with its reason, not as a failure. Tests now approve through the real policy writer and, end to end through createApp, assert the journal, the governance event and the next turn's policy facts. Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 1 + packages/ui-server/src/brain/sync-mirror.ts | 36 +++++-- packages/ui-server/src/routes/brain.ts | 13 ++- packages/ui-server/tests/sync-mirror.test.ts | 19 +++- .../ui-server/tests/sync-policy-app.test.ts | 96 +++++++++++++++++++ .../tests/sync-policy-review.test.ts | 21 +++- 6 files changed, 170 insertions(+), 16 deletions(-) create mode 100644 packages/ui-server/tests/sync-policy-app.test.ts diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 6693f1238e..7e5b4b6981 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -854,6 +854,7 @@ namespace mount points alone do not constrain the host publisher. > rationale shown is fixed host text. A Settings control for > `outward.github.repositories` was not taken: chat's `propose_policy_change` > already edits it. + Within one server process, maintenance clients serialize preparation through publication per canonical brain. Even readers produce SQLite projections or Git attribute objects in their private outputs; concurrent copies of that diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index c29be7e741..632bedec09 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -159,11 +159,21 @@ function refusedSync(local: ExecutionResult, reason: string): ExecutionResult { } /** What a refused tier A sync output says, and does, next (#4256). */ -async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintenanceOutputError, policy: { onPolicyChange?: (change: IncomingPolicyChange) => void; upstream?: string | null }): Promise { - if (error.paths.length === 1 && error.paths[0] === GOVERNANCE_POLICY_PATH) { +async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintenanceOutputError, policy: { + onPolicyChange?: (change: IncomingPolicyChange) => void; upstream?: string | null; + /** Whether `content` is exactly the upstream commit's policy blob, read by the host transport, never the worker. */ + verify?: (content: Uint8Array) => Promise; +}): Promise { + // Only the policy file, and the policy directory a first policy creates with it. + const policyOnly = error.paths.includes(GOVERNANCE_POLICY_PATH) + && error.paths.every(path => path === GOVERNANCE_POLICY_PATH || isWithin(path, GOVERNANCE_POLICY_PATH, { includeRoot: false }) && isWithin("context/policies", path)); + if (policyOnly && policy.upstream) { const content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); if (content && policy.onPolicyChange) { - policy.onPolicyChange({ content, upstream: policy.upstream ?? null }); + // A review offers only what the upstream commit itself carries: worker output is never a policy source. + if (!policy.verify || !await policy.verify(content)) + return refusedSync(local, `${error.message}. Nothing was published. The merged ${GOVERNANCE_POLICY_PATH} differs from the upstream commit's, so it cannot be reviewed: change the policy upstream so the brain's copy matches it, or revert the upstream commit.`); + policy.onPolicyChange({ content, upstream: policy.upstream }); return refusedSync(local, `Sync paused before publishing anything: the pull changes ${GOVERNANCE_POLICY_PATH}. Review the policy change; approving it adopts the policy, and the next sync completes.`); } if (content) return refusedSync(local, `Sync stopped before publishing anything: the pull changes ${GOVERNANCE_POLICY_PATH}, and a policy change needs the owner's review. Run Sync in the app to review it.`); @@ -172,7 +182,8 @@ async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintena return refusedSync(local, `${error.message}. Nothing was published. A sync never adopts this change: revert the upstream commit that makes it${policies ? `, then change the policy in chat (propose_policy_change)` : ""}.`); } -async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal; timeoutMs?: number; onPolicyChange?: (change: IncomingPolicyChange) => void; upstream?: string | null }, nativeManager: Parameters[1] | undefined, folderPaths?: readonly string[], log?: import("@opentelemetry/api-logs").Logger): Promise { +async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal; timeoutMs?: number; onPolicyChange?: (change: IncomingPolicyChange) => void; upstream?: string | null; + verify?: (content: Uint8Array) => Promise }, nativeManager: Parameters[1] | undefined, folderPaths?: readonly string[], log?: import("@opentelemetry/api-logs").Logger): Promise { if (!nativeManager) throw new Error("Local sync requires the configured native managed-storage manager; full-copy fallback is unavailable."); const view = await prepareNativeWorkerStartupView(command.brainPath, nativeManager, command.signal); let outputs: Awaited> | undefined; @@ -180,13 +191,13 @@ async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal command.signal?.throwIfAborted(); outputs = await prepareMaintenanceOutput(command.brainPath, { startupView: view, folderPaths, signal: command.signal }); const git = await prepareMaintenanceGit(command, outputs, command.signal, log); - const { onPolicyChange, upstream, ...worker } = command; + const { onPolicyChange, upstream, verify, ...worker } = command; const result = await runMaintenanceWorker({ ...worker, tempKind: "sync", startupView: outputs.view, output: outputs.output, ...(git ? { git } : {}) }); if (!result.killed) { try { await outputs.publish(); } catch (error) { if (!(error instanceof ProtectedMaintenanceOutputError) || result.exitCode !== 0) throw error; - return await protectedRefusal(result, error, { onPolicyChange, upstream }); + return await protectedRefusal(result, error, { onPolicyChange, upstream, verify }); } } return result; @@ -214,7 +225,8 @@ async function executeMirrorSync(input: Parameters[0]): Pr finally { await originView.cleanup(); } input.signal?.throwIfAborted(); input.onExecute?.(); - if (remote === null) return runLocalSync({ ...command, credentials: false, ...(input.onPolicyChange ? { onPolicyChange: input.onPolicyChange } : {}), + // Without a remote nothing is pulled, so no policy change can arrive: none is reviewable. + if (remote === null) return runLocalSync({ ...command, credentials: false, ...(input.signal ? { signal: input.signal } : {}), ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}) }, input.nativeManager, input.folderPaths, input.log); prepareMirror(mirror, brain); const transport = async (args: readonly string[]) => { @@ -231,8 +243,16 @@ async function executeMirrorSync(input: Parameters[0]): Pr // Entire config/commit/pull/merge/judgment/index flow stays in a worker // with no credential. Only objects and refs are writable in the mirror; // config, HEAD, hooks and the directory itself remain read-only. - last = await runLocalSync({ ...command, credentials: false, upstream: mirrorHead(mirror), + const upstream = mirrorHead(mirror); + last = await runLocalSync({ ...command, credentials: false, upstream, ...(input.onPolicyChange ? { onPolicyChange: input.onPolicyChange } : {}), + verify: async content => { + if (!upstream) return false; + const blob = await transport(["cat-file", "blob", `${upstream}:${GOVERNANCE_POLICY_PATH}`]); + let text: string; + try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content); } catch { return false; } + return blob.exitCode === 0 && blob.stdout === text; + }, readPaths: [...(command.readPaths ?? []), mirror], writeDirectories: [join(mirror, "objects"), join(mirror, "refs")], gitConfig: [["safe.directory", brain], ["safe.directory", mirror], [`url.file://${mirror}.insteadOf`, remote], ["remote.origin.pushurl", `file://${mirror}`]], diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index 45dc2a1faa..5398f74c76 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -131,12 +131,15 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { } catch (error) { unavailable(error); } } return { - end(failure: string | undefined, output: string) { + end(failure: string | undefined, output: string, paused?: string) { if (failure !== undefined) deps.log?.emit({ severityText: "ERROR", body: "ui sync failed", attributes: { error: failure.slice(0, 2_000) } }); + else if (paused !== undefined) deps.log?.emit({ severityText: "INFO", body: "ui sync paused for policy review", attributes: { reason: paused } }); if (!store || !started) return; try { if (output) observeWrite(store.appendEvent(spanId, "job_output", output, undefined, SYNC_OUTPUT_TAIL_CHARS), unavailable); - observeWrite(store.endSpan(spanId, failure === undefined ? { outcome: "success" } : { outcome: "error", reason: failure }), unavailable); + // A paused sync is not a failure (#4256): `cancelled` is the taxonomy's non-failure stop, with its reason. + observeWrite(store.endSpan(spanId, failure !== undefined ? { outcome: "error", reason: failure } + : paused !== undefined ? { outcome: "cancelled", reason: paused } : { outcome: "success" }), unavailable); observeWrite(store.rollupRun(runId), unavailable); } catch (error) { unavailable(error); } }, @@ -250,6 +253,7 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { let disconnected = false; let output = ""; let failure: string | undefined; + let paused: string | undefined; stream.onAbort(() => { disconnected = true; }); const send = (data: { type: string; @@ -394,6 +398,9 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { if (exitCode !== 0 && incoming && deps.policyReviews && principalId) { const opened = await openPolicyReview(principalId, incoming); if (opened.ok) { + // Paused, not failed: the run records why it is waiting. + failure = undefined; + paused = `Paused for the owner's review of an incoming ${GOVERNANCE_POLICY_PATH} change (exit ${exitCode}).`; await send({ type: "policy_review", ...opened.proposal }); await send({ type: "done", success: false, reason: "policy_review", text: "Sync paused: the pull changes the governance policy. Review it; after you approve, sync again." }); @@ -415,7 +422,7 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { } finally { clearInterval(keepalive); syncingRoots.delete(syncRoot); - run.end(failure, output); + run.end(failure, output, paused); } }); }) diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index ed5c65cba8..71392f1dd3 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -9,6 +9,9 @@ import { BrainSyncError, createBrainClient } from "../src/brain/client"; import { assertMirrorStorage, syncMirrorPath, syncTransportCommand } from "../src/brain/sync-mirror"; import { createHostExecution } from "../src/brain/host-execution"; import { createUiDb } from "../src/db/client"; +import { createPolicyProposals } from "../src/brain/policy-proposal"; +import { createOwnerPolicyReviews, OwnerPolicyReviewError } from "../src/brain/owner-policy-reviews"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; import { createNativeAppFixture } from "./helpers/native-app-fixture.js"; import { privateMaintenanceTest } from "./helpers/private-maintenance-test.js"; @@ -160,9 +163,19 @@ test("an upstream governance policy commit pauses a hosted sync for review, and expect(existsSync(join(f.brain, "context/policies/governance.md")), "UI_PUBLISHED_NOTHING").toBe(false); expect(existsSync(join(f.brain, "notes/sea.md")), "UI_PUBLISHED_NO_OTHER_FILE").toBe(false); - // What an approved review writes, through the policy writer, then the next sync completes. - mkdirSync(join(f.brain, "context/policies"), { recursive: true }); - writeFileSync(join(f.brain, "context/policies/governance.md"), policy); + // The owner approves the review through the real policy writer, then the next sync completes. + const db = createUiDb(":memory:"); + const active = new Set(); + const proposals = createPolicyProposals({ root: f.brain, db, lock: createKeyedLock(), + observeUserPolicy: (turnId, write) => { if (!active.has(turnId)) throw new Error("approved policy write requires a user window"); write(); }, + recordEvent: () => undefined }); + const reviews = createOwnerPolicyReviews({ root: f.brain, proposals, authorized: () => true, turnPrefix: "sync-policy", requestPrefix: "sync", + journal: { async begin(turnId) { active.add(turnId); }, async finish(turnId) { active.delete(turnId); } }, + fail: (status, code, message) => new OwnerPolicyReviewError(status, code, message) }); + try { + const opened = await reviews.propose("p-penelope", () => new TextDecoder().decode(changes[0]!.content), undefined, "Incoming from the remote", "invalid"); + expect((await reviews.decide("p-penelope", opened.turn_id, opened.request_id, true)).state, "REAL_APPROVAL_WRITES").toBe("updated"); + } finally { reviews.close(); db.close(); } const result = await client.sync().catch(error => { throw new Error(JSON.stringify(error.result) + "\n" + error.message); }); expect(result.result?.run.status, "ADOPTED_SYNC_COMPLETES").toBe("complete"); expect(readFileSync(join(f.brain, "context/policies/governance.md"), "utf8")).toBe(policy); diff --git a/packages/ui-server/tests/sync-policy-app.test.ts b/packages/ui-server/tests/sync-policy-app.test.ts new file mode 100644 index 0000000000..0d8c6242cc --- /dev/null +++ b/packages/ui-server/tests/sync-policy-app.test.ts @@ -0,0 +1,96 @@ +/** + * End to end through `createApp` and a real hosted sync (#4256): an upstream + * commit adds a governance policy, a UI sync pauses with a review of it, the + * owner approves through the decide route, the real journal records the write + * as a `user` `policy` change with a `policy_change` governance event, the + * next turn's policy facts carry the adopted policy, and the following sync + * completes. The brain is the Odysseus fixture corpus; the remote is a local + * bare repository outside it. + */ +import { afterEach, expect, test } from "bun:test"; +import { Database } from "bun:sqlite"; +import { chmodSync, cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { createNativeAppFixture, createFixtureApp as createApp } from "./helpers/native-app-fixture.js"; +import { createStaticBackendRegistry } from "../src/agent/backend"; +import { createRecordingObservability } from "../src/observability"; +import { resolveServerConfig } from "../src/config/env"; +import { makeFakeBackend } from "./helpers/fake-backend"; + +const ROOT = resolve(import.meta.dir, "../../.."); +const POLICY = "---\nschema_version: 1\noutward:\n github:\n repositories: [ithaca/*]\n---\nOdysseus decides what leaves Ithaca.\n"; +const roots: string[] = []; +const closers: Array<() => unknown> = []; +afterEach(async () => { + for (const close of closers.splice(0).reverse()) await close(); + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +function git(cwd: string, ...args: string[]) { + const result = Bun.spawnSync(["/usr/bin/git", ...args], { cwd, env: { PATH: "/usr/bin:/bin", HOME: "/nonexistent", GIT_CONFIG_GLOBAL: "/dev/null", GIT_CONFIG_NOSYSTEM: "1" } }); + if (result.exitCode !== 0) throw new Error(`git ${args.join(" ")}: ${result.stderr.toString()}`); + return result.stdout.toString().trim(); +} + +function fixture() { + const root = mkdtempSync(join(tmpdir(), "odysseus-sync-policy-app-")); roots.push(root); + const brain = join(root, "brain"), remote = join(root, "remote.git"), other = join(root, "other"); + cpSync(join(ROOT, "packages/core/fixtures/corpus"), brain, { recursive: true }); + writeFileSync(join(brain, ".gitignore"), "node_modules/\n.brain/\nbrain.db*\n"); + const config = readFileSync(join(brain, "brain.config.ts"), "utf8"); + writeFileSync(join(brain, "brain.config.ts"), config.replace('"@schlessera/brain"', JSON.stringify(join(ROOT, "packages/core/src/index.ts"))) + .replace("profile: {", 'agentRunner: "fixture-unavailable",\n profile: {')); + mkdirSync(remote); git(remote, "init", "--bare", "-b", "main"); + git(brain, "init", "-b", "main"); git(brain, "config", "user.name", "Odysseus"); git(brain, "config", "user.email", "odysseus@ithaca.example"); + git(brain, "add", "."); git(brain, "commit", "-m", "Harbor notebook"); + git(brain, "remote", "add", "origin", remote); git(brain, "push", "origin", "main"); + git(root, "clone", remote, other); + git(other, "config", "user.name", "Penelope"); git(other, "config", "user.email", "penelope@ithaca.example"); + mkdirSync(join(other, "context/policies"), { recursive: true }); + writeFileSync(join(other, "context/policies/governance.md"), POLICY); + git(other, "add", "."); git(other, "commit", "-m", "Open GitHub writes to Ithaca"); git(other, "push", "origin", "main"); + mkdirSync(join(brain, "node_modules/.bin"), { recursive: true }); + const cli = join(brain, "node_modules/.bin/brain"); + writeFileSync(cli, `#!/usr/bin/env bun\nawait import(${JSON.stringify(join(ROOT, "packages/core/src/cli/brain.ts"))});\n`); chmodSync(cli, 0o755); + const serverConfig = resolveServerConfig({ AUTH_MODE: "none", HOST: "127.0.0.1", NODE_ENV: "test", DB_PATH: join(root, "ui.db"), BRAIN_PATH: brain, BRAIN_UI_PRICING_DISCOVERY: "0" }); + const native = createNativeAppFixture(brain); closers.push(native.close); + serverConfig.nativeBrain = native.nativeBrain; + return { root, brain, remote, config: serverConfig }; +} + +const frames = async (response: Response) => (await response.text()).split("\n").filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6)) as Record); +const post = (path: string, body?: unknown) => new Request(`http://localhost${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body ?? {}) }); + +test("an upstream policy commit is reviewed, approved through the real journal, adopted for the next turn, and the next sync completes", async () => { + const f = fixture(); + const app = await createApp({ config: f.config, observability: createRecordingObservability(), registry: createStaticBackendRegistry([makeFakeBackend({ id: "fake" })]) }); + closers.push(() => app.close()); + const paused = await frames(await app.fetch(post("/api/brain/sync"))); + const review = paused.find(frame => frame.type === "policy_review") as { turn_id: string; request_id: string; review: { rationale: string } } | undefined; + expect(review, `APP_SYNC_REVIEWS: ${JSON.stringify(paused.slice(-3))}`).toBeDefined(); + expect(review!.review.rationale, "APP_REVIEW_NAMES_UPSTREAM").toContain(git(f.remote, "rev-parse", "main").slice(0, 12)); + expect(paused.at(-1)).toMatchObject({ type: "done", reason: "policy_review" }); + + const decided = await app.fetch(post(`/api/brain/sync/policy/${review!.turn_id}/${review!.request_id}`, { approve: true })); + expect(decided.status).toBe(200); + expect((await decided.json()).state, "APP_APPROVAL_WRITES").toBe("updated"); + expect(readFileSync(join(f.brain, "context/policies/governance.md"), "utf8"), "APP_INCOMING_BYTES_ADOPTED").toBe(POLICY); + + const db = new Database(f.config.dbPath, { readonly: true }); + try { + const change = db.query("SELECT class, actor FROM turn_journal_changes WHERE turn_id = ? AND path = 'context/policies/governance.md'").get(review!.turn_id); + expect(change, "APP_JOURNAL_USER_POLICY").toEqual({ class: "policy", actor: "user" }); + const event = db.query("SELECT kind, actor FROM governance_events WHERE turn_id = ? AND kind = 'policy_change'").get(review!.turn_id); + expect(event, "APP_POLICY_CHANGE_EVENT").toEqual({ kind: "policy_change", actor: "user" }); + } finally { db.close(); } + + // The policy facts the next admitted turn reads carry the adopted policy. + const facts = await (await app.fetch(new Request("http://localhost/api/agent-policy"))).json() as { source: string; hash: string | null; errors: string[] }; + expect(facts.errors, "APP_NEXT_TURN_POLICY_VALID").toEqual([]); + expect(facts.source, "APP_NEXT_TURN_POLICY_ADOPTED").toBe("policy"); + expect(facts.hash, "APP_NEXT_TURN_POLICY_HASH").toBe(new Bun.CryptoHasher("sha256").update(POLICY).digest("hex")); + + const completed = await frames(await app.fetch(post("/api/brain/sync"))); + expect(completed.at(-1), `APP_FOLLOWING_SYNC_COMPLETES: ${JSON.stringify(completed.slice(-4))}`).toMatchObject({ type: "done", success: true }); +}, 240_000); diff --git a/packages/ui-server/tests/sync-policy-review.test.ts b/packages/ui-server/tests/sync-policy-review.test.ts index 9ff4b27165..a392b8370a 100644 --- a/packages/ui-server/tests/sync-policy-review.test.ts +++ b/packages/ui-server/tests/sync-policy-review.test.ts @@ -16,6 +16,8 @@ import { createUiDb } from "../src/db/client.js"; import { createPolicyProposals } from "../src/brain/policy-proposal.js"; import { createOwnerPolicyReviews, OwnerPolicyReviewError, type OwnerPolicyJournal } from "../src/brain/owner-policy-reviews.js"; import { createBrainRoutes } from "../src/routes/brain"; +import { createActivityStore } from "../src/activity/store.js"; +import type { Logger, LogRecord } from "@opentelemetry/api-logs"; import type { BrainClient } from "../src/brain/client"; import type { HostBoundary, StreamingExecution } from "../src/brain/host-boundary"; import type { KeytermSettings } from "../src/voice/keyterm-builder"; @@ -75,7 +77,10 @@ function setup(root: string, launch?: HostBoundary["launch"]) { turnPrefix: "sync-policy", requestPrefix: "sync", fail: (status, code, message) => new OwnerPolicyReviewError(status, code, message) }); cleanup.push(() => reviews.close()); let launched = 0; - const routes = createBrainRoutes({ + const store = createActivityStore(db); + const logs: LogRecord[] = []; + const log = { emit: (record: LogRecord) => { logs.push(record); }, enabled: () => true } as unknown as Logger; + const routes = createBrainRoutes({ activity: store, log, brainPath: root, brain: { cliCommand: () => [process.execPath, "sync.ts"] } as BrainClient, keyterms: { brainPath: root } as KeytermSettings, exec: {}, policyReviews: reviews, boundary: { launch: launch ?? (async execution => { @@ -88,7 +93,7 @@ function setup(root: string, launch?: HostBoundary["launch"]) { const as = (principal: Principal) => new Hono().use("*", async (c, next) => { c.set("principal", principal); await next(); }).route("/api", routes); const family = (turnPrefix: string, requestPrefix: string) => createOwnerPolicyReviews({ root, proposals, journal, authorized: () => true, turnPrefix, requestPrefix, fail: (status, code, message) => new OwnerPolicyReviewError(status, code, message) }); - return { as, windows, events, launched: () => launched, family }; + return { as, windows, events, launched: () => launched, family, store, logs }; } const frames = async (response: Response) => (await response.text()).split("\n").filter(line => line.startsWith("data: ")).map(line => JSON.parse(line.slice(6)) as Record); @@ -111,6 +116,18 @@ describe("a sync's incoming policy change (#4256)", () => { expect(readFileSync(join(root, "context/policies/governance.md"), "utf8"), "NOTHING_WRITTEN_BEFORE_APPROVAL").toBe(CURRENT); }); + test("a paused sync's Activity run is not a failure, and nothing logs a sync failure", async () => { + const root = brain(); + const { as, store, logs } = setup(root); + await frames(await as(owner).request("/api/brain/sync", { method: "POST" })); + const span = store.changesSince(0).flatMap(change => change.kind === "span" ? [change.span] : []).find(span => span.jobName === "ui-sync")!; + const ended = store.getSpan(span.spanId)!; + expect(ended.outcome, "PAUSED_RUN_NOT_FAILED").toBe("cancelled"); + expect(ended.outcomeReason ?? "", "PAUSED_RUN_NAMES_REVIEW").toContain("Paused for the owner's review"); + expect(logs.some(record => record.body === "ui sync failed"), "PAUSED_NOT_LOGGED_AS_FAILURE").toBe(false); + expect(logs.some(record => record.body === "ui sync paused for policy review")).toBe(true); + }); + test("approval writes exactly the incoming bytes through the policy writer, in a user window", async () => { const root = brain(); const { as, windows, events } = setup(root); From 9807cf4b43a68e910b3b0ee17e3acae2facd8ad2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 15:38:23 +0000 Subject: [PATCH 07/21] test(ui-react): register the slide-panel DOM again on a repeated run (#4256) The determinism job repeats a changed file in one process; its module-body DOM registration ran once, so the second run had no window. Co-Authored-By: Claude Opus 5.5 --- packages/ui-react/tests/render/slide-panel-dom.ts | 13 ++++++++++--- packages/ui-react/tests/render/slide-panel.test.tsx | 9 ++++++--- 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/ui-react/tests/render/slide-panel-dom.ts b/packages/ui-react/tests/render/slide-panel-dom.ts index 5be04cd922..73dbd30941 100644 --- a/packages/ui-react/tests/render/slide-panel-dom.ts +++ b/packages/ui-react/tests/render/slide-panel-dom.ts @@ -8,10 +8,17 @@ import { GlobalRegistrator } from "@happy-dom/global-registrator"; import { act } from "react"; -if (!GlobalRegistrator.isRegistered) { - GlobalRegistrator.register(); +/** + * Register the DOM. The module body does it once, for the component imports + * that follow; a repeated run of the file (`--rerun-each`, the determinism + * job) reuses the loaded modules, so the file registers again before its + * tests through this. + */ +export function registerSlidePanelDom(): void { + if (!GlobalRegistrator.isRegistered) GlobalRegistrator.register(); + (globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; } -(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true; +registerSlidePanelDom(); export async function unregisterSlidePanelDom(): Promise { if (GlobalRegistrator.isRegistered) { diff --git a/packages/ui-react/tests/render/slide-panel.test.tsx b/packages/ui-react/tests/render/slide-panel.test.tsx index 2c571a58c2..411cae8f16 100644 --- a/packages/ui-react/tests/render/slide-panel.test.tsx +++ b/packages/ui-react/tests/render/slide-panel.test.tsx @@ -3,9 +3,11 @@ // so a stray click cancelled the run. Same containment contract as // render-smoke.test.tsx: the DOM module first, `afterAll(unregisterDom)`, // queries off `render()` and never `screen`. -import { unregisterSlidePanelDom as unregisterDom } from "./slide-panel-dom.js"; +import { registerSlidePanelDom, unregisterSlidePanelDom as unregisterDom } from "./slide-panel-dom.js"; -import { afterAll, afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, mock, test } from "bun:test"; +// A repeated run of this file reuses its modules: register the DOM again before its tests. +beforeAll(registerSlidePanelDom); import { overlayGeometry } from "./overlay-geometry.js"; let restoreGeometry: () => void; @@ -29,7 +31,8 @@ afterAll(async () => { }); const realFetch = globalThis.fetch; -const realMatchMedia = window.matchMedia; +let realMatchMedia: typeof window.matchMedia; +beforeAll(() => { realMatchMedia = window.matchMedia; }); afterEach(() => { globalThis.fetch = realFetch; window.matchMedia = realMatchMedia; From 16ebb52d7c5ec5d1f94c1fd5c7c24c51fdde39b4 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 15:49:38 +0000 Subject: [PATCH 08/21] fix(ui-sdk): the plain output publisher refuses tier A changes with the same typed error (#4256) Co-Authored-By: Claude Opus 5.5 --- packages/ui-sdk/src/server/worker-output.ts | 25 +++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/packages/ui-sdk/src/server/worker-output.ts b/packages/ui-sdk/src/server/worker-output.ts index 9ac2f95a84..b53cefd963 100644 --- a/packages/ui-sdk/src/server/worker-output.ts +++ b/packages/ui-sdk/src/server/worker-output.ts @@ -8,6 +8,7 @@ import { join, resolve } from "node:path"; import { createWorkerStartupView, type WorkerStartupView } from "./worker-startup-view.js"; import { createOutputStagingStorage } from "./worker-launcher.js"; import { isEnvName, PROTECTED_TIER_A } from "./protected-paths.js"; +import { ProtectedMaintenanceOutputError } from "./protected-output-error.js"; /** A named writable work area. Configuration executes at the original brain path, read-only. */ export const WORKER_OUTPUT = "/tmp/brain-maintenance-output"; @@ -83,6 +84,27 @@ function parent(root: string, rel: string): { fd: number; name: string } { } catch (error) { closeSync(fd); throw error; } } +/** One output file's bytes, opened without following links; null when absent or not a regular file. */ +function readOutputFile(root: string, rel: string, bound: number): Uint8Array | null { + let handle: ReturnType; + try { handle = parent(root, rel); } + catch (error) { if (["ENOENT", "ENOTDIR"].includes((error as NodeJS.ErrnoException).code ?? "")) return null; throw error; } + try { + let fd: number; + try { fd = openSync(at(handle.fd, handle.name), constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); } + catch (error) { if (["ENOENT", "ELOOP"].includes((error as NodeJS.ErrnoException).code ?? "")) return null; throw error; } + try { + const info = fstatSync(fd); + if (!info.isFile()) return null; + if (info.size > bound) throw new Error(`Refused output ${rel} exceeds ${bound} bytes`); + const bytes = Buffer.alloc(info.size); + let read = 0; + while (read < bytes.length) { const n = readSync(fd, bytes, read, bytes.length - read, null); if (!n) break; read += n; } + return bytes.subarray(0, read); + } finally { closeSync(fd); } + } finally { closeSync(handle.fd); } +} + function current(root: string, rel: string): Entry | undefined { let handle: ReturnType; try { handle = parent(root, rel); } @@ -119,6 +141,9 @@ export function prepareWorkerOutput(brain: string, options: { startupView?: Work } const selected = (rel: string) => !options.areas || options.areas.some(area => isWithin(area, rel)); const changed = [...new Set([...before.keys(), ...after.keys()])].filter(rel => selected(rel) && !equalOutput(before.get(rel), after.get(rel))); + // Every refused tier A change, named before anything is written (#4256). + const refused = changed.filter(rel => isEnvName(rel.split("/")[0]!) || PROTECTED_TIER_A.some(path => isWithin(path, rel))); + if (refused.length) throw new ProtectedMaintenanceOutputError(refused, async (rel, bound) => readOutputFile(output.root, rel, bound)); for (const rel of changed) { const previous = before.get(rel); const next = after.get(rel); From 551f333f7c8fabf172417cae48955205505f25d6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:07:26 +0000 Subject: [PATCH 09/21] test(ui-server): read the journal from its own database; accept an unreadable covered file Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/sync-policy-app.test.ts | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/tests/sync-policy-app.test.ts b/packages/ui-server/tests/sync-policy-app.test.ts index 0d8c6242cc..d25363f04b 100644 --- a/packages/ui-server/tests/sync-policy-app.test.ts +++ b/packages/ui-server/tests/sync-policy-app.test.ts @@ -17,6 +17,7 @@ import { createStaticBackendRegistry } from "../src/agent/backend"; import { createRecordingObservability } from "../src/observability"; import { resolveServerConfig } from "../src/config/env"; import { makeFakeBackend } from "./helpers/fake-backend"; +import { journalDatabasePath } from "../src/db/journal-database"; const ROOT = resolve(import.meta.dir, "../../.."); const POLICY = "---\nschema_version: 1\noutward:\n github:\n repositories: [ithaca/*]\n---\nOdysseus decides what leaves Ithaca.\n"; @@ -77,10 +78,13 @@ test("an upstream policy commit is reviewed, approved through the real journal, expect((await decided.json()).state, "APP_APPROVAL_WRITES").toBe("updated"); expect(readFileSync(join(f.brain, "context/policies/governance.md"), "utf8"), "APP_INCOMING_BYTES_ADOPTED").toBe(POLICY); - const db = new Database(f.config.dbPath, { readonly: true }); + const journal = new Database(journalDatabasePath(f.config.dbPath), { readonly: true }); try { - const change = db.query("SELECT class, actor FROM turn_journal_changes WHERE turn_id = ? AND path = 'context/policies/governance.md'").get(review!.turn_id); + const change = journal.query("SELECT class, actor FROM turn_journal_changes WHERE turn_id = ? AND path = 'context/policies/governance.md'").get(review!.turn_id); expect(change, "APP_JOURNAL_USER_POLICY").toEqual({ class: "policy", actor: "user" }); + } finally { journal.close(); } + const db = new Database(f.config.dbPath, { readonly: true }); + try { const event = db.query("SELECT kind, actor FROM governance_events WHERE turn_id = ? AND kind = 'policy_change'").get(review!.turn_id); expect(event, "APP_POLICY_CHANGE_EVENT").toEqual({ kind: "policy_change", actor: "user" }); } finally { db.close(); } From 02d944745a58b0d35e053ce85cc13e6797d9b6b9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:28:46 +0000 Subject: [PATCH 10/21] fix(ui-server): read the upstream policy blob before the worker runs, without replace objects (#4256) A sync worker can write the mirror's objects and refs, so the blob it is compared with is now read after the integrity check and fetch and before the worker, and every transport runs with GIT_NO_REPLACE_OBJECTS. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/sync-mirror.ts | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 632bedec09..e4ccf0446d 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -100,7 +100,9 @@ export function syncTransportCommand(input: { brain: string; mirror: string; rem const readPaths: string[] = []; const writePaths: string[] = []; const env: Record = { PATH: "/usr/bin:/bin", HOME: "/tmp/brain-maintenance-home", GIT_CONFIG_NOSYSTEM: "1", - GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0" }; + GIT_CONFIG_GLOBAL: "/dev/null", GIT_TERMINAL_PROMPT: "0", + // A worker can write the mirror's refs: a replace ref must never change what an object reads as (#4256). + GIT_NO_REPLACE_OBJECTS: "1" }; let remote = input.remote; if (remote.startsWith("/") || remote.startsWith("file://")) { const path = realpathSync(remote.startsWith("file://") ? new URL(remote).pathname : remote); @@ -243,15 +245,17 @@ async function executeMirrorSync(input: Parameters[0]): Pr // Entire config/commit/pull/merge/judgment/index flow stays in a worker // with no credential. Only objects and refs are writable in the mirror; // config, HEAD, hooks and the directory itself remain read-only. + // The upstream policy is read now, after the integrity check and the fetch + // and before any worker of this sync runs, so worker writes to the mirror + // cannot change what it is compared with. const upstream = mirrorHead(mirror); + const upstreamPolicy = upstream && input.onPolicyChange ? await transport(["cat-file", "blob", `${upstream}:${GOVERNANCE_POLICY_PATH}`]) : null; + const expected = upstreamPolicy?.exitCode === 0 ? upstreamPolicy.stdout : null; last = await runLocalSync({ ...command, credentials: false, upstream, ...(input.onPolicyChange ? { onPolicyChange: input.onPolicyChange } : {}), verify: async content => { - if (!upstream) return false; - const blob = await transport(["cat-file", "blob", `${upstream}:${GOVERNANCE_POLICY_PATH}`]); - let text: string; - try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content); } catch { return false; } - return blob.exitCode === 0 && blob.stdout === text; + if (expected === null) return false; + try { return new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content) === expected; } catch { return false; } }, readPaths: [...(command.readPaths ?? []), mirror], writeDirectories: [join(mirror, "objects"), join(mirror, "refs")], From 34ecb7ed45464e35b571451f27a3943335294597 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:30:23 +0000 Subject: [PATCH 11/21] test(ui-server): MUTATION, reverted next commit: the boundary drops onPolicyChange, as before #4256 Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/host-boundary.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 4333ee10ee..5322fedd33 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -654,7 +654,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { } return credentialed(admission, async () => { if (execution.sync) return outputLock.withLock(brain, () => runMirrorSync({ log: options.log, nativeManager: options.nativeManager, folderPaths: hold?.folderPaths, command: command(execution), transportEnv: execution.env, mirror: mirror ??= syncMirrorPath(brain, options.dbPath), - ...(execution.onPolicyChange ? { onPolicyChange: execution.onPolicyChange } : {}), ...(execution.signal ? { signal: execution.signal } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }), { signal: admissionSignal }); + ...(execution.signal ? { signal: execution.signal } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }), { signal: admissionSignal }); const run = async () => { admissionSignal?.throwIfAborted(); execution.assertAuthorized?.(); @@ -730,7 +730,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { const onAbort = () => abort.abort(execution.signal?.reason); execution.signal?.addEventListener("abort", onAbort, { once: true }); const exited = runMirrorSync({ log: options.log, nativeManager: options.nativeManager, folderPaths: hold?.folderPaths, command: selectedCommand, transportEnv: execution.env, mirror: selectedMirror, signal: abort.signal, - ...(execution.onExecute ? { onExecute: execution.onExecute } : {}), ...(execution.onPolicyChange ? { onPolicyChange: execution.onPolicyChange } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { + ...(execution.onExecute ? { onExecute: execution.onExecute } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { stdout.write(result.stdout); stderr.write(result.stderr); return result.exitCode; }, error => { stderr.write(error instanceof Error ? error.message : String(error)); return 1; }) .finally(async () => { From bb3d16c42844d11f64a32b157701ab3c2931dfd2 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:36:33 +0000 Subject: [PATCH 12/21] test(ui-server): restore the boundary's onPolicyChange forwarding (#4256) Reverts the mutation commit, whose hosted run 44774074901 failed the native sync-mirror test at UI_SYNC_PAUSED_TEXT as expected. Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/host-boundary.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/brain/host-boundary.ts b/packages/ui-server/src/brain/host-boundary.ts index 5322fedd33..4333ee10ee 100644 --- a/packages/ui-server/src/brain/host-boundary.ts +++ b/packages/ui-server/src/brain/host-boundary.ts @@ -654,7 +654,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { } return credentialed(admission, async () => { if (execution.sync) return outputLock.withLock(brain, () => runMirrorSync({ log: options.log, nativeManager: options.nativeManager, folderPaths: hold?.folderPaths, command: command(execution), transportEnv: execution.env, mirror: mirror ??= syncMirrorPath(brain, options.dbPath), - ...(execution.signal ? { signal: execution.signal } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }), { signal: admissionSignal }); + ...(execution.onPolicyChange ? { onPolicyChange: execution.onPolicyChange } : {}), ...(execution.signal ? { signal: execution.signal } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }), { signal: admissionSignal }); const run = async () => { admissionSignal?.throwIfAborted(); execution.assertAuthorized?.(); @@ -730,7 +730,7 @@ export function createHostBoundary(options: HostBoundaryOptions): HostBoundary { const onAbort = () => abort.abort(execution.signal?.reason); execution.signal?.addEventListener("abort", onAbort, { once: true }); const exited = runMirrorSync({ log: options.log, nativeManager: options.nativeManager, folderPaths: hold?.folderPaths, command: selectedCommand, transportEnv: execution.env, mirror: selectedMirror, signal: abort.signal, - ...(execution.onExecute ? { onExecute: execution.onExecute } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { + ...(execution.onExecute ? { onExecute: execution.onExecute } : {}), ...(execution.onPolicyChange ? { onPolicyChange: execution.onPolicyChange } : {}), ...(execution.timeoutMs ? { timeoutMs: execution.timeoutMs } : {}) }).then(result => { stdout.write(result.stdout); stderr.write(result.stderr); return result.exitCode; }, error => { stderr.write(error instanceof Error ? error.message : String(error)); return 1; }) .finally(async () => { From d751b95f77f4fbe8458ac71394f087ea06b1a523 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:46:38 +0000 Subject: [PATCH 13/21] fix(ui-server, ui-react): a paused sync shows as waiting; newer sync reviews replace stale ones; state the blob rule (#4256) Co-Authored-By: Claude Opus 5.5 --- docs/decisions/governed-writable-workers.md | 28 +++++++++++-------- .../quick-actions/streaming-modal.tsx | 2 +- .../quick-actions/streaming-output.tsx | 4 ++- .../tests/render/slide-panel.test.tsx | 2 ++ .../src/brain/owner-policy-reviews.ts | 10 +++++++ packages/ui-server/src/routes/brain.ts | 2 ++ .../tests/sync-policy-review.test.ts | 16 +++++++++++ 7 files changed, 51 insertions(+), 13 deletions(-) diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 7e5b4b6981..24c917e452 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -841,17 +841,23 @@ namespace mount points alone do not constrain the host publisher. > ([#4256](https://github.com/schlessera/brain-kit/issues/4256), maintainer ruling option 1).** > The policy file is versioned host input, so a pull is where a policy change > arrives. The refusal above still holds: a hosted sync's worker output never -> publishes a tier A change. When the only refused path is -> `context/policies/governance.md`, the host reads the output's bytes before -> cleanup, publishes nothing, and opens a host-owned review of them through the -> existing policy proposals, the only policy writer, as Settings › Apify does -> (`createOwnerPolicyReviews`, `packages/ui-server/src/brain/owner-policy-reviews.ts`). -> Only the owner whose UI sync opened it can answer, and only an approval -> writes, in a `user` journal window. The next sync then merges the identical -> change cleanly. A scheduled sync opens no review and names the waiting change. -> Every other tier A change keeps its refusal, with next-step text. No agent -> runtime, worker or autonomous turn proposes or answers these reviews, and the -> rationale shown is fixed host text. A Settings control for +> publishes a tier A change. When the only refused paths are +> `context/policies/governance.md` and the `context/policies` directory a first +> policy creates with it, on a sync with a remote, the host compares the stage's +> bytes with the upstream commit's own policy blob. The host transport reads that +> blob after the integrity check and the fetch, before the sync's worker runs, +> with replace objects disabled. Only equal bytes are reviewable, so worker output +> is never a policy source. The host then publishes nothing and opens a host-owned +> review through the existing policy proposals, the only policy writer, as +> Settings › Apify does (`createOwnerPolicyReviews`, +> `packages/ui-server/src/brain/owner-policy-reviews.ts`). A newer sync's review +> replaces the owner's unanswered one. Only the owner whose UI sync opened it can +> answer, and only an approval writes, in a `user` journal window. The next sync +> then merges the identical change cleanly. A scheduled sync opens no review and +> names the waiting change. Any other tier A change, a merged policy that differs +> from upstream's, or a sync without a remote keeps the refusal, with next-step +> text. No agent runtime, worker or autonomous turn proposes or answers these +> reviews, and the rationale shown is fixed host text. A Settings control for > `outward.github.repositories` was not taken: chat's `propose_policy_change` > already edits it. diff --git a/packages/ui-react/src/components/quick-actions/streaming-modal.tsx b/packages/ui-react/src/components/quick-actions/streaming-modal.tsx index 813bc5a0b4..d225eeb9de 100644 --- a/packages/ui-react/src/components/quick-actions/streaming-modal.tsx +++ b/packages/ui-react/src/components/quick-actions/streaming-modal.tsx @@ -98,7 +98,7 @@ export function StreamingPanel({ } if (data.type === "done") { finished = true; - setState(data.success ? "success" : "error"); + setState(data.success ? "success" : data.reason === "policy_review" ? "waiting" : "error"); } } catch {} } diff --git a/packages/ui-react/src/components/quick-actions/streaming-output.tsx b/packages/ui-react/src/components/quick-actions/streaming-output.tsx index 8073e32e11..60ab657a45 100644 --- a/packages/ui-react/src/components/quick-actions/streaming-output.tsx +++ b/packages/ui-react/src/components/quick-actions/streaming-output.tsx @@ -15,7 +15,8 @@ import type { Tone } from "@schlessera/brain-ui-kit"; * failure or a cancellation — and the row is a polite live region so a * screen reader hears "Complete" once, not every line. */ -export type StreamState = "idle" | "running" | "success" | "error" | "cancelled"; +/** `waiting`: the job paused for an owner answer (a sync's incoming policy review, #4256), not a failure. */ +export type StreamState = "idle" | "running" | "success" | "error" | "cancelled" | "waiting"; const STATUS: Record = { idle: { tone: "neutral", pulse: false, text: "Ready" }, @@ -23,6 +24,7 @@ const STATUS: Record success: { tone: "teal", pulse: false, text: "Complete" }, error: { tone: "red", pulse: false, text: "Failed" }, cancelled: { tone: "red", pulse: false, text: "Cancelled" }, + waiting: { tone: "amber", pulse: false, text: "Waiting for your policy review" }, }; interface StreamingOutputProps { diff --git a/packages/ui-react/tests/render/slide-panel.test.tsx b/packages/ui-react/tests/render/slide-panel.test.tsx index 411cae8f16..86e754210f 100644 --- a/packages/ui-react/tests/render/slide-panel.test.tsx +++ b/packages/ui-react/tests/render/slide-panel.test.tsx @@ -425,6 +425,8 @@ describe("StreamingPanel sync policy review (#4256)", () => { ].map(frame => `data: ${JSON.stringify(frame)}\n\n`).join(""); await act(async () => { requests[0]!.response.resolve(new Response(frames)); await flushPromises(); }); expect(view.getByText("Sync paused: the pull changes the governance policy.")).toBeTruthy(); + expect(view.getByText("Waiting for your policy review"), "PAUSED_SYNC_NOT_FAILED").toBeTruthy(); + expect(view.queryByText("Failed")).toBeNull(); const card = view.baseElement.querySelector("[data-sync-policy-review]"); expect(card?.getAttribute("data-policy-state"), "SYNC_REVIEW_RENDERED").toBe("pending"); expect(card?.textContent).toContain("4b1d0c0ffee4"); diff --git a/packages/ui-server/src/brain/owner-policy-reviews.ts b/packages/ui-server/src/brain/owner-policy-reviews.ts index 356a51fe95..cad3186782 100644 --- a/packages/ui-server/src/brain/owner-policy-reviews.ts +++ b/packages/ui-server/src/brain/owner-policy-reviews.ts @@ -127,6 +127,16 @@ export function createOwnerPolicyReviews(options: OwnerPolicyReviewOptions) { if (!recorded) throw options.fail(404, "not_found", "No policy review is open for this request."); return recorded; }, + /** + * Decline this owner's open reviews in this family and wait for them to + * settle: a newer review of the same source replaces them, so unanswered + * ones a closed panel can no longer show never reach the cap. + */ + async supersede(principalId: string): Promise { + const open = [...pending.values()].filter(entry => entry.principalId === principalId); + for (const entry of open) entry.answer(false); + await Promise.allSettled(open.map(entry => entry.done)); + }, /** Decline every open review: shutdown or test teardown. */ close() { for (const entry of pending.values()) entry.answer(false); }, }; diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index 5398f74c76..a5cf05ff0f 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -153,6 +153,8 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { catch { return { ok: false as const, message: `The incoming ${GOVERNANCE_POLICY_PATH} is not UTF-8 text, so it cannot be reviewed. Revert the upstream commit that changes it.` }; } const rationale = `Incoming from the brain's remote${change.upstream ? ` at commit ${change.upstream.slice(0, 12)}` : ""}: the pull changes ${GOVERNANCE_POLICY_PATH}. Approving adopts it, and the next sync completes.`; try { + // This sync's review is the current one: an older unanswered sync review is declined, never left to fill the cap. + await deps.policyReviews!.supersede(principalId); return { ok: true as const, proposal: await deps.policyReviews!.propose(principalId, () => text, undefined, rationale, `The incoming policy did not validate, so nothing was proposed. Revert the upstream commit that changes ${GOVERNANCE_POLICY_PATH}, or fix it there`) }; } catch (error) { diff --git a/packages/ui-server/tests/sync-policy-review.test.ts b/packages/ui-server/tests/sync-policy-review.test.ts index a392b8370a..72b3e3354f 100644 --- a/packages/ui-server/tests/sync-policy-review.test.ts +++ b/packages/ui-server/tests/sync-policy-review.test.ts @@ -154,6 +154,22 @@ describe("a sync's incoming policy change (#4256)", () => { expect(launched()).toBe(2); }); + test("unanswered reviews never fill the cap: each sync's review replaces the owner's older one", async () => { + const root = brain(); + const { as } = setup(root); + const reviews: Record[] = []; + for (let i = 0; i < 6; i++) { + const all = await frames(await as(owner).request("/api/brain/sync", { method: "POST" })); + const review = all.find(frame => frame.type === "policy_review"); + expect(review, `SYNC_${i}_REVIEWS_AGAIN: ${JSON.stringify(all.at(-1))}`).toBeDefined(); + reviews.push(review!); + } + // The superseded reviews were declined: answering one now returns its recorded receipt and writes nothing. + expect((await (await decide(as(owner), reviews[0]!, true)).json()).state, "SUPERSEDED_REVIEW_DECLINED").toBe("declined"); + expect(readFileSync(join(root, "context/policies/governance.md"), "utf8")).toBe(CURRENT); + expect((await (await decide(as(owner), reviews.at(-1)!, true)).json()).state, "CURRENT_REVIEW_APPROVES").toBe("updated"); + }); + test("another principal or an unknown review is refused, and nothing is written", async () => { const root = brain(); const { as, family } = setup(root); From f92b99db1b587dac16fefdd38ffdbc9b1daa91e3 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 16:55:30 +0000 Subject: [PATCH 14/21] fix(ui-server): a scheduled sync verifies the upstream policy blob before naming a review (#4256) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/sync-mirror.ts | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index e4ccf0446d..052664834a 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -171,14 +171,16 @@ async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintena && error.paths.every(path => path === GOVERNANCE_POLICY_PATH || isWithin(path, GOVERNANCE_POLICY_PATH, { includeRoot: false }) && isWithin("context/policies", path)); if (policyOnly && policy.upstream) { const content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); - if (content && policy.onPolicyChange) { + if (content) { // A review offers only what the upstream commit itself carries: worker output is never a policy source. + // A scheduled sync decides the same way, so it never names a review a UI sync would refuse. if (!policy.verify || !await policy.verify(content)) return refusedSync(local, `${error.message}. Nothing was published. The merged ${GOVERNANCE_POLICY_PATH} differs from the upstream commit's, so it cannot be reviewed: change the policy upstream so the brain's copy matches it, or revert the upstream commit.`); + if (!policy.onPolicyChange) + return refusedSync(local, `Sync stopped before publishing anything: the pull changes ${GOVERNANCE_POLICY_PATH}, and a policy change needs the owner's review. Run Sync in the app to review it.`); policy.onPolicyChange({ content, upstream: policy.upstream }); return refusedSync(local, `Sync paused before publishing anything: the pull changes ${GOVERNANCE_POLICY_PATH}. Review the policy change; approving it adopts the policy, and the next sync completes.`); } - if (content) return refusedSync(local, `Sync stopped before publishing anything: the pull changes ${GOVERNANCE_POLICY_PATH}, and a policy change needs the owner's review. Run Sync in the app to review it.`); } const policies = error.paths.some(path => isWithin("context/policies", path)); return refusedSync(local, `${error.message}. Nothing was published. A sync never adopts this change: revert the upstream commit that makes it${policies ? `, then change the policy in chat (propose_policy_change)` : ""}.`); @@ -249,7 +251,7 @@ async function executeMirrorSync(input: Parameters[0]): Pr // and before any worker of this sync runs, so worker writes to the mirror // cannot change what it is compared with. const upstream = mirrorHead(mirror); - const upstreamPolicy = upstream && input.onPolicyChange ? await transport(["cat-file", "blob", `${upstream}:${GOVERNANCE_POLICY_PATH}`]) : null; + const upstreamPolicy = upstream ? await transport(["cat-file", "blob", `${upstream}:${GOVERNANCE_POLICY_PATH}`]) : null; const expected = upstreamPolicy?.exitCode === 0 ? upstreamPolicy.stdout : null; last = await runLocalSync({ ...command, credentials: false, upstream, ...(input.onPolicyChange ? { onPolicyChange: input.onPolicyChange } : {}), From c425cd8a85b7c25b3dc1a0ff6aaf80e7b2b16e5a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:09:04 +0000 Subject: [PATCH 15/21] fix(ui-server, ui-react): bound the upstream policy read; show the review inside the panel's scroll area (#4256) Co-Authored-By: Claude Opus 5.5 --- .../src/components/quick-actions/streaming-modal.tsx | 2 +- .../src/components/quick-actions/streaming-output.tsx | 3 +++ packages/ui-server/src/brain/sync-mirror.ts | 9 +++++---- 3 files changed, 9 insertions(+), 5 deletions(-) diff --git a/packages/ui-react/src/components/quick-actions/streaming-modal.tsx b/packages/ui-react/src/components/quick-actions/streaming-modal.tsx index d225eeb9de..5b5ba438cf 100644 --- a/packages/ui-react/src/components/quick-actions/streaming-modal.tsx +++ b/packages/ui-react/src/components/quick-actions/streaming-modal.tsx @@ -157,8 +157,8 @@ export function StreamingPanel({ setLines((lines) => [...lines, "Cancelled."]); }} onClose={onClose} + after={policyReview && } /> - {policyReview && } ); } diff --git a/packages/ui-react/src/components/quick-actions/streaming-output.tsx b/packages/ui-react/src/components/quick-actions/streaming-output.tsx index 60ab657a45..025029cf7e 100644 --- a/packages/ui-react/src/components/quick-actions/streaming-output.tsx +++ b/packages/ui-react/src/components/quick-actions/streaming-output.tsx @@ -35,6 +35,8 @@ interface StreamingOutputProps { onClose: () => void; /** Wire to the scroll anchor the container keeps in view. */ anchor?: ReactNode; + /** Shown after the log, inside the same scrolling area, above the footer (a sync's policy review, #4256). */ + after?: ReactNode; } export function StreamingOutput(p: StreamingOutputProps) { @@ -54,6 +56,7 @@ export function StreamingOutput(p: StreamingOutputProps) { ))} {running && p.lines.length === 0 &&
Starting...
} + {p.after &&
{p.after}
} {p.anchor} diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 052664834a..5d65ce5f96 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -233,10 +233,10 @@ async function executeMirrorSync(input: Parameters[0]): Pr if (remote === null) return runLocalSync({ ...command, credentials: false, ...(input.signal ? { signal: input.signal } : {}), ...(input.timeoutMs ? { timeoutMs: input.timeoutMs } : {}) }, input.nativeManager, input.folderPaths, input.log); prepareMirror(mirror, brain); - const transport = async (args: readonly string[]) => { + const transport = async (args: readonly string[], outputBytes?: number) => { assertMirrorStorage(mirror); return runMaintenanceWorker({ ...syncTransportCommand({ brain, mirror, remote, env: input.transportEnv ?? command.env, args, tempLimits: command.tempLimits, tempDomain: command.tempDomain }), - ...(input.signal ? { signal: input.signal } : {}), timeoutMs: input.timeoutMs ?? 120_000 }); + ...(input.signal ? { signal: input.signal } : {}), ...(outputBytes ? { outputBytes } : {}), timeoutMs: input.timeoutMs ?? 120_000 }); }; let last: ExecutionResult = { stdout: "", stderr: "", exitCode: 1 }; for (let attempt = 0; attempt < 3; attempt++) { @@ -251,8 +251,9 @@ async function executeMirrorSync(input: Parameters[0]): Pr // and before any worker of this sync runs, so worker writes to the mirror // cannot change what it is compared with. const upstream = mirrorHead(mirror); - const upstreamPolicy = upstream ? await transport(["cat-file", "blob", `${upstream}:${GOVERNANCE_POLICY_PATH}`]) : null; - const expected = upstreamPolicy?.exitCode === 0 ? upstreamPolicy.stdout : null; + // Bounded like the stage read: a larger upstream policy is never held, and it cannot be reviewed. + const upstreamPolicy = upstream ? await transport(["cat-file", "blob", `${upstream}:${GOVERNANCE_POLICY_PATH}`], INCOMING_POLICY_READ_BOUND) : null; + const expected = upstreamPolicy?.exitCode === 0 && !upstreamPolicy.killed ? upstreamPolicy.stdout : null; last = await runLocalSync({ ...command, credentials: false, upstream, ...(input.onPolicyChange ? { onPolicyChange: input.onPolicyChange } : {}), verify: async content => { From d197e3377c49f79a53160feb89fa04886214df4b Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:18:31 +0000 Subject: [PATCH 16/21] fix(ui-server): name the right next step for every refusal (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/sync-mirror.ts | 9 +++++++-- packages/ui-server/tests/sync-mirror.test.ts | 1 + 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 5d65ce5f96..19e06e4cfd 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -170,7 +170,9 @@ async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintena const policyOnly = error.paths.includes(GOVERNANCE_POLICY_PATH) && error.paths.every(path => path === GOVERNANCE_POLICY_PATH || isWithin(path, GOVERNANCE_POLICY_PATH, { includeRoot: false }) && isWithin("context/policies", path)); if (policyOnly && policy.upstream) { - const content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); + let content: Uint8Array | null; + try { content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); } + catch { return refusedSync(local, `${error.message}. Nothing was published. The incoming ${GOVERNANCE_POLICY_PATH} exceeds the policy writer's 1 MiB bound, so it cannot be reviewed: shrink it upstream, or revert the upstream commit that makes it.`); } if (content) { // A review offers only what the upstream commit itself carries: worker output is never a policy source. // A scheduled sync decides the same way, so it never names a review a UI sync would refuse. @@ -183,7 +185,10 @@ async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintena } } const policies = error.paths.some(path => isWithin("context/policies", path)); - return refusedSync(local, `${error.message}. Nothing was published. A sync never adopts this change: revert the upstream commit that makes it${policies ? `, then change the policy in chat (propose_policy_change)` : ""}.`); + // Only a sync that pulled has an upstream commit to name; otherwise the change came from the brain itself. + const source = policy.upstream ? "revert the upstream commit that makes it, or remove the change from the brain's repository if the sync made it" + : "remove the change from the brain's repository"; + return refusedSync(local, `${error.message}. Nothing was published. A sync never adopts this change: ${source}${policies ? `, then change the policy in chat (propose_policy_change)` : ""}.`); } async function runLocalSync(command: MaintenanceCommand & { signal?: AbortSignal; timeoutMs?: number; onPolicyChange?: (change: IncomingPolicyChange) => void; upstream?: string | null; diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index 71392f1dd3..d1d3100cf1 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -202,6 +202,7 @@ test("an upstream change to another tier A input keeps its refusal and says what const text = await stderr; expect(text, "TIER_A_REFUSED").toContain("maintenance output cannot change protected input bunfig.toml"); expect(text, "TIER_A_NEXT_STEP").toContain("revert the upstream commit"); + expect(text, "TIER_A_NEXT_STEP_NAMES_LOCAL_SOURCE").toContain("remove the change from the brain's repository"); expect(changes, "TIER_A_NOT_REVIEWABLE").toEqual([]); expect(existsSync(join(f.brain, "bunfig.toml"))).toBe(false); } finally { server.stop(true); } From cbf48210a13b43d00993dac9d930e0291beefd7c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:28:47 +0000 Subject: [PATCH 17/21] fix(ui-server): truthful sync review rationale and reports; relay refusals, lost writes and bounds recorded (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- docs/http-api.md | 24 +++++++++++---------- packages/ui-server/src/brain/sync-mirror.ts | 6 +++++- packages/ui-server/src/routes/brain.ts | 3 ++- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/docs/http-api.md b/docs/http-api.md index e2b1d9ed3d..c7a68961bd 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -628,7 +628,12 @@ concurrent attempts get 409 `{ error, heldMs }` before SSE starts, where the error text names it in seconds. The route invokes `brain sync --human`. Disconnecting the reader stops delivery but **does not cancel sync or release its reservation**; output continues draining until the -child exits. +child exits. Successful sync attempts voice keyterm rebuild; a rebuild failure +is progress text and does not turn successful sync into failure. A degraded +rebuild (no usable core peer, or an index core cannot read) is reported as +progress text and not cached. A canonical +root-resolution failure before admission can use the common 500. No idempotency +key or SSE resumption promise exists. **Bounded start (additive, #4257).** Everything between admission and the sync's first worker starting (the CLI version probe, the writer gate, the @@ -650,8 +655,8 @@ whose only tier A change is `context/policies/governance.md` publishes nothing. When the requesting principal is a current owner, the stream sends `{ type: "policy_review", turn_id, request_id, review }`, where `review` is the same `PolicyChangeReview` a chat policy card shows (base hash, frontmatter -diff, changed sections, body diff, and a fixed host rationale naming the -upstream commit), and ends with `{ type: "done", success: false, reason: +diff, changed sections, body diff, and a fixed host rationale saying the +brain's remote has this version at the named upstream commit), and ends with `{ type: "done", success: false, reason: "policy_review", text }`. The owner answers it through `POST /api/brain/sync/policy/:turnId/:requestId`. Approval writes exactly the incoming bytes through the existing policy writer (journal actor `user`, class @@ -660,14 +665,11 @@ it, and the next sync completes. Decline writes nothing, and the next sync opens the review again. An incoming policy that is not UTF-8 or does not validate opens no review: a progress line names the next step and the sync fails. A scheduled sync opens no review; it fails naming the waiting change. -Any other refused tier A change keeps its refusal, and its text says to revert -the upstream commit (and, under `context/policies/`, to change the policy in -chat with `propose_policy_change`). Successful sync attempts voice keyterm rebuild; a rebuild failure -is progress text and does not turn successful sync into failure. A degraded -rebuild (no usable core peer, or an index core cannot read) is reported as -progress text and not cached. A canonical -root-resolution failure before admission can use the common 500. No idempotency -key or SSE resumption promise exists. +Any other refused tier A change keeps its refusal, and its text says what to do +next: revert the upstream commit, or remove a change the brain itself made +(and, under `context/policies/`, change the policy in chat with +`propose_policy_change`). A refused sync's human report is replaced by that +reason, since nothing was published or pushed. ## Sessions and execution records diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index 19e06e4cfd..de7964590f 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -156,7 +156,11 @@ function refusedSync(local: ExecutionResult, reason: string): ExecutionResult { result.run.report = `${reason}\n${typeof result.run.report === "string" ? result.run.report : ""}`; stdout = JSON.stringify(result); } - } catch { /* Human-mode output keeps its report; stderr carries the reason. */ } + else stdout = ""; + } catch { + // A human report would describe commits and a push that never published: the reason replaces it. + stdout = ""; + } return { stdout, stderr: reason, exitCode: 1 }; } diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index a5cf05ff0f..a19ea5c38f 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -151,7 +151,8 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { let text: string; try { text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(change.content); } catch { return { ok: false as const, message: `The incoming ${GOVERNANCE_POLICY_PATH} is not UTF-8 text, so it cannot be reviewed. Revert the upstream commit that changes it.` }; } - const rationale = `Incoming from the brain's remote${change.upstream ? ` at commit ${change.upstream.slice(0, 12)}` : ""}: the pull changes ${GOVERNANCE_POLICY_PATH}. Approving adopts it, and the next sync completes.`; + // Truthful whatever made the stage differ: the review offers exactly the upstream commit's own version. + const rationale = `The brain's remote has a different ${GOVERNANCE_POLICY_PATH}${change.upstream ? ` at commit ${change.upstream.slice(0, 12)}` : ""}. Approving adopts that version, and the next sync completes.`; try { // This sync's review is the current one: an older unanswered sync review is declined, never left to fill the cap. await deps.policyReviews!.supersede(principalId); From 0f091ba24fef08cb1e0aad1ae3784964a82a178a Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:41:42 +0000 Subject: [PATCH 18/21] fix(ui-server): name the right refusals and launch class (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- docs/http-api.md | 5 ++--- packages/ui-server/src/brain/sync-mirror.ts | 2 ++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/http-api.md b/docs/http-api.md index c7a68961bd..b538c1dca1 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -662,9 +662,8 @@ brain's remote has this version at the named upstream commit), and ends with `{ incoming bytes through the existing policy writer (journal actor `user`, class `policy`, a `policy_change` governance event); the next admitted turn reads it, and the next sync completes. Decline writes nothing, and the next sync -opens the review again. An incoming policy that is not UTF-8 or does not -validate opens no review: a progress line names the next step and the sync -fails. A scheduled sync opens no review; it fails naming the waiting change. +opens the review again. An incoming policy that is not UTF-8, exceeds 1 MiB or does not validate +opens no review: the sync fails, and its text names the next step. A scheduled sync opens no review; it fails naming the waiting change. Any other refused tier A change keeps its refusal, and its text says what to do next: revert the upstream commit, or remove a change the brain itself made (and, under `context/policies/`, change the policy in chat with diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index de7964590f..dce3b59906 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -178,6 +178,8 @@ async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintena try { content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); } catch { return refusedSync(local, `${error.message}. Nothing was published. The incoming ${GOVERNANCE_POLICY_PATH} exceeds the policy writer's 1 MiB bound, so it cannot be reviewed: shrink it upstream, or revert the upstream commit that makes it.`); } if (content) { + try { new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content); } + catch { return refusedSync(local, `${error.message}. Nothing was published. The incoming ${GOVERNANCE_POLICY_PATH} is not UTF-8 text, so it cannot be reviewed: fix its encoding upstream, or revert the upstream commit that makes it.`); } // A review offers only what the upstream commit itself carries: worker output is never a policy source. // A scheduled sync decides the same way, so it never names a review a UI sync would refuse. if (!policy.verify || !await policy.verify(content)) From bf7744157fd3daeabd50fd31766a39245e71a973 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 17:52:38 +0000 Subject: [PATCH 19/21] fix(ui-server): record the real cause of a refused sync review; every relayed write in the run output (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/routes/brain.ts | 2 ++ packages/ui-server/tests/sync-policy-review.test.ts | 4 +++- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/src/routes/brain.ts b/packages/ui-server/src/routes/brain.ts index a19ea5c38f..3a9a57a3ed 100644 --- a/packages/ui-server/src/routes/brain.ts +++ b/packages/ui-server/src/routes/brain.ts @@ -410,6 +410,8 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { return; } await send({ type: "progress", text: opened.message }); + // The run records the real cause, not the paused text of a review that never opened. + failure = `Sync failed (exit ${exitCode}): ${opened.message}`; } await send({ diff --git a/packages/ui-server/tests/sync-policy-review.test.ts b/packages/ui-server/tests/sync-policy-review.test.ts index 72b3e3354f..aeab6414ef 100644 --- a/packages/ui-server/tests/sync-policy-review.test.ts +++ b/packages/ui-server/tests/sync-policy-review.test.ts @@ -190,7 +190,7 @@ describe("a sync's incoming policy change (#4256)", () => { test("an incoming policy that does not validate fails the sync with next steps and opens no review", async () => { const root = brain(); - const { as } = setup(root, async execution => { + const { as, logs } = setup(root, async execution => { execution.onExecute?.(); execution.onPolicyChange?.({ content: new TextEncoder().encode("---\nschema_version: 99\n---\n"), upstream: null }); return failedProcess(); @@ -198,6 +198,8 @@ describe("a sync's incoming policy change (#4256)", () => { const all = await frames(await as(owner).request("/api/brain/sync", { method: "POST" })); expect(all.some(frame => frame.type === "policy_review"), "INVALID_OPENS_NO_REVIEW").toBe(false); expect(all.some(frame => frame.type === "progress" && String(frame.text).includes("Revert the upstream commit")), "INVALID_NAMES_NEXT_STEP").toBe(true); + const failed = logs.find(record => record.body === "ui sync failed"); + expect(String(failed?.attributes?.error), "INVALID_RUN_RECORDS_REAL_CAUSE").toContain("did not validate"); expect(all.at(-1)).toMatchObject({ type: "done", success: false }); expect(readFileSync(join(root, "context/policies/governance.md"), "utf8")).toBe(CURRENT); }); From 8f3bbd654a55fb2b043ac8b516f1d8e11e8b2a2d Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:03:45 +0000 Subject: [PATCH 20/21] fix(ui-server): record a sync policy read failure by its cause; native edit-path test; relay settles in-flight writes and names settings (review of #4256/#4259) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/src/brain/sync-mirror.ts | 7 ++- packages/ui-server/tests/sync-mirror.test.ts | 46 ++++++++++++++++++++ 2 files changed, 52 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/src/brain/sync-mirror.ts b/packages/ui-server/src/brain/sync-mirror.ts index dce3b59906..927a8deacc 100644 --- a/packages/ui-server/src/brain/sync-mirror.ts +++ b/packages/ui-server/src/brain/sync-mirror.ts @@ -176,7 +176,12 @@ async function protectedRefusal(local: ExecutionResult, error: ProtectedMaintena if (policyOnly && policy.upstream) { let content: Uint8Array | null; try { content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); } - catch { return refusedSync(local, `${error.message}. Nothing was published. The incoming ${GOVERNANCE_POLICY_PATH} exceeds the policy writer's 1 MiB bound, so it cannot be reviewed: shrink it upstream, or revert the upstream commit that makes it.`); } + catch (cause) { + const message = cause instanceof Error ? cause.message : String(cause); + return refusedSync(local, /exceeds \d+ bytes/.test(message) + ? `${error.message}. Nothing was published. The incoming ${GOVERNANCE_POLICY_PATH} exceeds the policy writer's 1 MiB bound, so it cannot be reviewed: shrink it upstream, or revert the upstream commit that makes it.` + : `${error.message}. Nothing was published. The incoming ${GOVERNANCE_POLICY_PATH} could not be read for review (${message.slice(0, 200)}); sync again, and if it persists, revert the upstream commit that makes it.`); + } if (content) { try { new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(content); } catch { return refusedSync(local, `${error.message}. Nothing was published. The incoming ${GOVERNANCE_POLICY_PATH} is not UTF-8 text, so it cannot be reviewed: fix its encoding upstream, or revert the upstream commit that makes it.`); } diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index d1d3100cf1..44a5fe7871 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -183,6 +183,52 @@ test("an upstream governance policy commit pauses a hosted sync for review, and } finally { server.stop(true); } }, 180_000); +test("an upstream commit that edits an existing governance policy pauses for review, and its approval lets the next sync complete (#4256)", async () => { + const f = fixture(); + const before = "---\nschema_version: 1\n---\nOdysseus decides what leaves Ithaca.\n"; + const after = "---\nschema_version: 1\noutward:\n github:\n repositories: [ithaca/*]\n---\nOdysseus decides what leaves Ithaca.\n"; + // The brain already has a policy, committed and pushed. + mkdirSync(join(f.brain, "context/policies"), { recursive: true }); + writeFileSync(join(f.brain, "context/policies/governance.md"), before); + git(f.brain, "add", "context/policies/governance.md"); git(f.brain, "commit", "-m", "Ithaca policy"); git(f.brain, "push", "origin", "main"); + const other = join(f.root, "other"); + git(other, "pull", "--quiet", "origin", "main"); + writeFileSync(join(other, "context/policies/governance.md"), after); + git(other, "add", "."); git(other, "commit", "-m", "Open GitHub writes to Ithaca"); git(other, "push", "origin", "main"); + const boundary = createHostBoundary({ brainPath: f.brain, nativeManager: f.nativeManager, dbPath: f.dbPath }); + const server = fixtureRemote(f.root, f.remote); + git(f.brain, "remote", "set-url", "origin", `${server.url}remote.git`); + try { + const changes: { content: Uint8Array; upstream: string | null }[] = []; + const proc = await boundary.launch({ argv: [join(f.brain, "node_modules/.bin/brain"), "sync", "--human"], env: { PATH: process.env.PATH }, + credentials: false, gate: "exclusive", sync: true, purpose: "policy edit review sync", onPolicyChange: change => { changes.push(change); } }); + void new Response(proc.stdout).text().catch(() => {}); + const stderr = new Response(proc.stderr).text(); + expect(await proc.exited, "EDIT_SYNC_PAUSED_EXIT").toBe(1); + expect(await stderr, "EDIT_SYNC_PAUSED_TEXT").toContain("Sync paused before publishing anything"); + expect(changes.map(change => new TextDecoder().decode(change.content)), "EDIT_INCOMING_BYTES_EXACT").toEqual([after]); + expect(readFileSync(join(f.brain, "context/policies/governance.md"), "utf8"), "EDIT_PUBLISHED_NOTHING").toBe(before); + + const db = createUiDb(":memory:"); + const active = new Set(); + const proposals = createPolicyProposals({ root: f.brain, db, lock: createKeyedLock(), + observeUserPolicy: (turnId, write) => { if (!active.has(turnId)) throw new Error("approved policy write requires a user window"); write(); }, + recordEvent: () => undefined }); + const reviews = createOwnerPolicyReviews({ root: f.brain, proposals, authorized: () => true, turnPrefix: "sync-policy", requestPrefix: "sync", + journal: { async begin(turnId) { active.add(turnId); }, async finish(turnId) { active.delete(turnId); } }, + fail: (status, code, message) => new OwnerPolicyReviewError(status, code, message) }); + try { + const opened = await reviews.propose("p-penelope", () => after, undefined, "Remote policy", "invalid"); + expect(opened.review.baseHash, "EDIT_REVIEW_HAS_BASE").not.toBeNull(); + expect((await reviews.decide("p-penelope", opened.turn_id, opened.request_id, true)).state, "EDIT_APPROVAL_WRITES").toBe("updated"); + } finally { reviews.close(); db.close(); } + const client = createBrainClient({ brainPath: f.brain, boundary, exec: {} }); + const result = await client.sync().catch(error => { throw new Error(JSON.stringify(error.result) + "\n" + error.message); }); + expect(result.result?.run.status, "EDIT_NEXT_SYNC_COMPLETES").toBe("complete"); + expect(readFileSync(join(f.brain, "context/policies/governance.md"), "utf8")).toBe(after); + } finally { server.stop(true); } +}, 180_000); + test("an upstream change to another tier A input keeps its refusal and says what to do next (#4256)", async () => { const f = fixture(); const boundary = createHostBoundary({ brainPath: f.brain, nativeManager: f.nativeManager, dbPath: f.dbPath }); From c1eebc46d5e47aa82b511778c41a531c11d73e96 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 18:13:56 +0000 Subject: [PATCH 21/21] test(ui-server): the edit-path fixture takes the upstream note before pushing its policy (#4256) Co-Authored-By: Claude Opus 5.5 --- packages/ui-server/tests/sync-mirror.test.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/packages/ui-server/tests/sync-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index 44a5fe7871..8b24f2f09a 100644 --- a/packages/ui-server/tests/sync-mirror.test.ts +++ b/packages/ui-server/tests/sync-mirror.test.ts @@ -187,7 +187,8 @@ test("an upstream commit that edits an existing governance policy pauses for rev const f = fixture(); const before = "---\nschema_version: 1\n---\nOdysseus decides what leaves Ithaca.\n"; const after = "---\nschema_version: 1\noutward:\n github:\n repositories: [ithaca/*]\n---\nOdysseus decides what leaves Ithaca.\n"; - // The brain already has a policy, committed and pushed. + // The brain already has a policy, committed and pushed (after taking the fixture's upstream note). + git(f.brain, "pull", "--quiet", "--no-rebase", "origin", "main"); mkdirSync(join(f.brain, "context/policies"), { recursive: true }); writeFileSync(join(f.brain, "context/policies/governance.md"), before); git(f.brain, "add", "context/policies/governance.md"); git(f.brain, "commit", "-m", "Ithaca policy"); git(f.brain, "push", "origin", "main");