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/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 diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 880d709aaf..0b01043c72 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -836,6 +836,31 @@ 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 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. + 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..b538c1dca1 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. @@ -627,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 @@ -642,12 +648,27 @@ 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 -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. +`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 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 +`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, 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 +`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/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..5b5ba438cf 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,12 +89,16 @@ 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]); } if (data.type === "done") { finished = true; - setState(data.success ? "success" : "error"); + setState(data.success ? "success" : data.reason === "policy_review" ? "waiting" : "error"); } } catch {} } @@ -149,6 +157,7 @@ export function StreamingPanel({ setLines((lines) => [...lines, "Cancelled."]); }} onClose={onClose} + after={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 8073e32e11..025029cf7e 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 { @@ -33,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) { @@ -52,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-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-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 cb22ea8d2b..86e754210f 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; @@ -399,3 +402,48 @@ 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(); + 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"); + 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-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-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); diff --git a/packages/ui-server/src/apify/settings.ts b/packages/ui-server/src/apify/settings.ts index d2653ab029..a892181ae0 100644 --- a/packages/ui-server/src/apify/settings.ts +++ b/packages/ui-server/src/apify/settings.ts @@ -14,18 +14,17 @@ * 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"; -import type { PolicyChangeReview } from "@schlessera/brain-ui-sdk/tool-contracts"; 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 +231,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 +243,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..cad3186782 --- /dev/null +++ b/packages/ui-server/src/brain/owner-policy-reviews.ts @@ -0,0 +1,144 @@ +/** + * 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 } + +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"; + } +} + +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; + +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; } +} + +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 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); }, + }; +} +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..927a8deacc 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"; @@ -99,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); @@ -133,7 +136,74 @@ 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); + } + 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 }; +} + +/** 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; + /** 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) { + let content: Uint8Array | null; + try { content = await error.read(GOVERNANCE_POLICY_PATH, INCOMING_POLICY_READ_BOUND); } + 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.`); } + // 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.`); + } + } + const policies = error.paths.some(path => isWithin("context/policies", path)); + // 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; + 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; @@ -141,8 +211,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, 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, verify }); + } + } return result; } finally { try { await outputs?.cleanup(); } finally { await view.cleanup(); } } } @@ -150,7 +227,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,13 +245,14 @@ async function executeMirrorSync(input: Parameters[0]): Pr finally { await originView.cleanup(); } input.signal?.throwIfAborted(); input.onExecute?.(); + // 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[]) => { + 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++) { @@ -183,7 +263,19 @@ 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, + // 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); + // 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 => { + 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")], gitConfig: [["safe.directory", brain], ["safe.directory", mirror], [`url.file://${mirror}.insteadOf`, remote], ["remote.origin.pushurl", `file://${mirror}`]], @@ -202,6 +294,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..3a9a57a3ed 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; @@ -123,18 +131,38 @@ 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); } }, }; } + /** 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.` }; } + // 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); + 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"); @@ -228,14 +256,15 @@ 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; 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 +288,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 +320,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 +395,25 @@ 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) { + // 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." }); + 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({ type: "done", success: exitCode === 0, @@ -377,11 +427,30 @@ export function createBrainRoutes(deps: BrainRoutesDeps): Hono { } finally { clearInterval(keepalive); syncingRoots.delete(syncRoot); - run.end(failure, output); + run.end(failure, output, paused); } }); }) + // 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-mirror.test.ts b/packages/ui-server/tests/sync-mirror.test.ts index a2ab5c81c2..8b24f2f09a 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"; @@ -126,6 +129,132 @@ 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); + + // 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); + expect(readFileSync(join(f.brain, "notes/sea.md"), "utf8")).toContain("Telemachus watches the tide."); + } 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 (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"); + 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 }); + 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(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); } +}, 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-app.test.ts b/packages/ui-server/tests/sync-policy-app.test.ts new file mode 100644 index 0000000000..d25363f04b --- /dev/null +++ b/packages/ui-server/tests/sync-policy-app.test.ts @@ -0,0 +1,100 @@ +/** + * 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"; +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"; +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 journal = new Database(journalDatabasePath(f.config.dbPath), { readonly: true }); + try { + 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(); } + + // 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 new file mode 100644 index 0000000000..aeab6414ef --- /dev/null +++ b/packages/ui-server/tests/sync-policy-review.test.ts @@ -0,0 +1,206 @@ +/** + * 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 { 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"; + +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 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 => { + 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); + 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, 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); +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)", () => { + 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("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); + 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([String(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("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); + 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); + // 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); + }); + + test("an incoming policy that does not validate fails the sync with next steps and opens no review", async () => { + const root = brain(); + const { as, logs } = 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); + 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); + }); +});