From 7e2fd503f16b7b54738582289718b864f1530205 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 14:21:21 +0000 Subject: [PATCH 1/2] CONTRACT: reject ambiguous proposed policy frontmatter (#3666) --- .../strict-policy-proposal-frontmatter.md | 5 ++ docs/decisions/frontmatter-parsing.md | 27 ++++++- docs/decisions/governed-writable-workers.md | 4 +- docs/integration-contract/mcp.md | 12 +++ docs/plans/reviewable-session-safety.md | 2 +- .../ui-server/src/brain/policy-proposal.ts | 17 +++- .../tests/bridge-capabilities.test.ts | 30 +++++++- .../ui-server/tests/policy-proposal.test.ts | 77 ++++++++++++++----- 8 files changed, 149 insertions(+), 25 deletions(-) create mode 100644 .changeset/strict-policy-proposal-frontmatter.md diff --git a/.changeset/strict-policy-proposal-frontmatter.md b/.changeset/strict-policy-proposal-frontmatter.md new file mode 100644 index 0000000000..475bc0a7ac --- /dev/null +++ b/.changeset/strict-policy-proposal-frontmatter.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +BREAKING (pre-1.0, approved for 0.45.0): `propose_policy_change` now refuses previously accepted unclosed frontmatter, annotated opening fences such as `---yaml`, and closing prefixes such as `---x` or `----` before approval. Submit closed, standalone `---` delimiter lines, optionally followed by spaces/tabs. Accepted BOM, LF/CRLF and EOF forms retain exact bytes; valid replacements can still repair existing ambiguous policies. Other frontmatter parser callers are unchanged. diff --git a/docs/decisions/frontmatter-parsing.md b/docs/decisions/frontmatter-parsing.md index db2380ab91..0ea088a4a6 100644 --- a/docs/decisions/frontmatter-parsing.md +++ b/docs/decisions/frontmatter-parsing.md @@ -134,7 +134,7 @@ write: | `brain tags --apply` and the key editor | two `frontmatterBounds`/`readScalar` pairs; the tags copy searched back from the block's end and took the closing fence into the block when a `---` rule followed it | one pair, in `frontmatter-edit.ts`; an unclosed block has no bounds | | hygiene log files | BOM (frontmatter read as body and rewritten) | the parser's opening; **stricter closing**: a block not closed by a `---` line with only whitespace after it is refused, including `----`, `---x` and `...` closers the parser would end at or run past, because hygiene rewrites the body | | ui-react `splitFrontmatter` | BOM; a closing fence at the end of the file | the parser's, except that an unclosed block is shown as body rather than swallowed, so the viewer never hides text | -| ui-server policy review `split` | accepts a `...` closer | unchanged for now; open on #2507 | +| ui-server policy review `split` | accepted a `...` closer | the parser's boundary for existing bytes; proposed bytes require strict standalone fences (#3666) | Rule 3 of the gate (`scanFences`, `scripts/check-frontmatter-parse.ts:222-252`) refuses a hand-written detector in package source: a non-multiline regex @@ -143,6 +143,31 @@ and `indexOf`/`lastIndexOf("\n---…")`. Files that emit or post-process a fence they wrote, and the pending policy splitter, are listed in `FENCE_ALLOWED` with a reason each. +## Hosted policy proposals (#3666, maintainer decision 2026-11-08) + +New `propose_policy_change` content must use closed, standalone `---` +delimiter lines, allowing trailing spaces/tabs. The proposal service locates +boundaries with `frontmatterBlock` and inspects those delimiter lines; it +rejects unclosed blocks, opening annotations/suffixes (`---yaml`, `---x`) +and closing prefixes (`---x`, `---yaml`, `----`) before requesting approval, +and reapplies the rule at publication. It never searches for a later, +cleaner closing fence or repairs submitted bytes. + +The maintainer selected this proposal-specific narrowing as a pre-1.0 +breaking change for 0.45.0. An approval review should not ask an owner to +resolve ambiguous policy delimiters. A rejected proposal returns a validation +error, with no actionable card, policy publication, journal edit or policy +change event. Correcting the proposal clears the refusal automatically; it +does not disable other requests or require a host restart. + +The shared data-only parser intentionally remains broader, including its +support for annotated YAML elsewhere. Existing policy bytes retain its +parser-aligned frontmatter/body split, even when malformed, so a valid new +proposal can repair them. Valid BOM, LF/CRLF, trailing delimiter whitespace +and EOF closing fences retain exact-byte publication. Normalizing either side, +globally tightening the parser, or refusing repairs because old fences are +ambiguous would exceed the selected policy. + ## Rejected alternatives - **Pass `{}` at every call site (O1).** This was already half-done, and the diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index 9c25a99843..4c4c3c5964 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1194,7 +1194,7 @@ replacement and the deadline publish nothing and record no policy-updated event; a no-publication attempt records none either. Real observation and storage failures keep their existing handling, and a publication that committed before its report failed stays `unknown` and is never retried -(`const held`, `packages/ui-server/src/brain/policy-proposal.ts:150-239`). +(`const held`, `packages/ui-server/src/brain/policy-proposal.ts:159-254`). Every retained turn has one initially collapsed receipt. Known no-change is zero; legacy/unknown detail and unknown cost/limits remain explicitly unknown. @@ -1210,7 +1210,7 @@ principal authority remain the caller's responsibility. The policy publisher creates, writes, fsyncs and removes its operation-owned staging name entirely inside that synchronous callback, between the two serialized observations (`await options.observeUserPolicy`, -`packages/ui-server/src/brain/policy-proposal.ts:202-236`). First publication +`packages/ui-server/src/brain/policy-proposal.ts:217-251`). First publication also removes the temporary hardlink before the final observation. No filename prefix is ignored; a similarly named real agent change is still retained. Failed staging preserves the original policy, while failed recording after diff --git a/docs/integration-contract/mcp.md b/docs/integration-contract/mcp.md index fba3ede499..d9b01bcb47 100644 --- a/docs/integration-contract/mcp.md +++ b/docs/integration-contract/mcp.md @@ -1461,6 +1461,18 @@ checkpoint delegates to this validation/write route; the eventual tool handler reconciles the same tool-use identity rather than executing a second write. A remembered tool grant cannot authorize a policy change. Speech never grants. +**Breaking input narrowing for 0.45.0 (#3666, maintainer-approved pre-1.0 +break):** proposed frontmatter must have closed, standalone `---` delimiter +lines, with optional trailing spaces/tabs. Unclosed blocks, annotated/suffixed +openings such as `---yaml` or `---x`, and parser-recognized closing prefixes +such as `---x`, `---yaml` or `----` are refused before approval or any pending +actionable card. Refusal publishes no file bytes, journal edit or policy-change +event. Migration: submit standalone, closed `---` fences. BOM, LF/CRLF and an +EOF closing fence remain supported; accepted content is published byte for +byte without normalization. The same validation runs again at publication. +This rule applies only to proposed bytes: a valid replacement can repair an +old ambiguous policy, whose review retains the shared parser's boundaries. + A valid card names the exact base hash (null for no file), frontmatter diff, changed section names, body-change indicator/body diff and quoted agent rationale. Decline writes nothing. Approve and write revalidates under diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index a9a274a5c6..4f158d1d02 100644 --- a/docs/plans/reviewable-session-safety.md +++ b/docs/plans/reviewable-session-safety.md @@ -50,7 +50,7 @@ public design or its fixtures. Fictional examples use the Odysseus world. (`GovernancePolicySchema`, `packages/common/src/governance-policy.ts:101-130`). The privileged proposal writer already provides exact-base review, descriptor-bound publication, authority rechecks and crash receipts - (`createPolicyProposals`, `packages/ui-server/src/brain/policy-proposal.ts:76-240`). + (`createPolicyProposals`, `packages/ui-server/src/brain/policy-proposal.ts:100-275`). - Private reference access already matches canonical repository prefixes and live principal grants; that is access authority, not content trust ([reference-source grants](../decisions/reference-source-grants.md)). Its diff --git a/packages/ui-server/src/brain/policy-proposal.ts b/packages/ui-server/src/brain/policy-proposal.ts index 35b18ef2d7..640a3304a2 100644 --- a/packages/ui-server/src/brain/policy-proposal.ts +++ b/packages/ui-server/src/brain/policy-proposal.ts @@ -61,6 +61,15 @@ function split(text: string) { const end = rest ? block.innerEnd + 3 + rest[0].length : block.end; return { frontmatter: text.slice(0, end), body: text.slice(end) }; } +/** Proposal-only strictness (#3666); existing policy bytes keep the parser's broader rule. */ +function proposalBoundaryError(text: string): string | null { + const block = frontmatterBlock(text); + if (!block || !block.closed) return "Proposed policy frontmatter must have closed, standalone --- delimiter lines (optional trailing spaces/tabs)."; + // Inspect only the delimiter positions found by the shared parser, never search for a later fence. + const standalone = (offset: number) => /^[ \t]*(?:\r?\n|$)/.test(text.slice(offset + 3)); + return standalone(block.start) && standalone(block.innerEnd) ? null + : "Proposed policy frontmatter delimiters must be standalone --- lines (optional trailing spaces/tabs); suffixes and annotations are not accepted."; +} function sections(before: string, after: string) { let a: Record = {}; try { a = parseFrontmatter(before, { dataOnly: true }).data; } catch { /* Invalid current bytes are still reviewed exactly. */ } @@ -172,7 +181,13 @@ export function createPolicyProposals(options: { if (row.input_hash !== inputHash || !readReview(turn.principalId, turn.turnId, requestId)) throw new Error("Policy proposal id already belongs to another request."); return active.get(key) ?? readReview(turn.principalId, turn.turnId, requestId)!; } - const bytes = Buffer.from(input.content, "utf8"), validate = options.validate ?? parseGovernancePolicy; + const bytes = Buffer.from(input.content, "utf8"); + const validate = (value: Buffer) => { + const checked = (options.validate ?? parseGovernancePolicy)(value); + if (!checked.ok || checked.status !== "valid") return checked; + const error = proposalBoundaryError(value.toString("utf8")); + return error ? { ...checked, ok: false as const, errors: [error] } : checked; + }; const checked = validate(bytes); if (!checked.ok || checked.status !== "valid") throw new Error(`Invalid policy: ${checked.errors.join("; ")}`); const root = resolvedRoot ??= realpathSync(options.root); diff --git a/packages/ui-server/tests/bridge-capabilities.test.ts b/packages/ui-server/tests/bridge-capabilities.test.ts index ba5fb268a3..723eaaf50f 100644 --- a/packages/ui-server/tests/bridge-capabilities.test.ts +++ b/packages/ui-server/tests/bridge-capabilities.test.ts @@ -4,7 +4,7 @@ * (`ws-claude-effects`, `provider-mask-bridge`, `inbox-bridge-tools`). */ import { expect, test } from "bun:test"; -import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { createKeyedLock, type BackendBridge, type PermissionDecision } from "@schlessera/brain-ui-sdk/server"; @@ -22,6 +22,7 @@ import { ProviderRecordsRefusedError } from "../src/brain/provider-mask-refusal. import { createPermissions } from "../src/ws/bridge-capabilities/permissions.js"; import { createAsks } from "../src/ws/bridge-capabilities/asks.js"; import { createLocationAndMask, createMaskApplicationSlice } from "../src/ws/bridge-capabilities/location-mask.js"; +import { createPolicyProposals } from "../src/brain/policy-proposal.js"; import { createPolicyProposal } from "../src/ws/bridge-capabilities/policy-proposal.js"; import { createApplication } from "../src/ws/bridge-capabilities/application.js"; import { createScratch } from "../src/ws/bridge-capabilities/scratch.js"; @@ -295,3 +296,30 @@ test("live authority: a revoked turn's attachment read never runs", async () => expect(ran).toBe(0); } finally { f.cleanup(); } }); + +for (const backendId of ["claude", "pi"]) test(`policy proposal: ${backendId} bridge rejects ambiguous bytes before permission or card (#3666)`, async () => { + const f = fixture({ backendId }), db = createUiDb(":memory:"); + const original = "---\nschema_version: 1\n---\nOdysseus reviews.\n"; + const path = join(f.root, "context/policies/governance.md"); + mkdirSync(join(f.root, "context/policies"), { recursive: true }); writeFileSync(path, original); + let approvals = 0, observations = 0, events = 0; + const service = createPolicyProposals({ root: f.root, db, lock: createKeyedLock(), + observeUserPolicy: (_id, write) => { observations++; write(); }, recordEvent: () => { events++; } }); + Object.assign(f.host, { policyProposals: service }); + // Even a remembered allow must never see malformed proposals. + const bridge = { requestPermission: async () => { approvals++; return { behavior: "allow" }; } } as unknown as BackendBridge; + const slice = createPolicyProposal(f.ctx, () => bridge); + try { + for (const content of ["---\nschema_version: 1\n", ...["---x", "---yaml", "----"].flatMap(fence => [ + original.replace(/^---/, fence), original.replace("1\n---", `1\n${fence}`), + ])]) { + await expect(slice.proposePolicyChange!("ambiguous", { content, rationale: "Review the policy." })).rejects.toThrow("Invalid policy"); + expect(approvals).toBe(0); expect(observations).toBe(0); expect(events).toBe(0); expect(f.frames).toEqual([]); + expect(db.query("SELECT count(*) AS n FROM policy_proposals").get()).toEqual({ n: 0 }); + expect(readFileSync(path, "utf8")).toBe(original); + } + const content = original.replace("reviews", "approves"); + expect((await slice.proposePolicyChange!("repair", { content, rationale: "Review the policy." })).state).toBe("updated"); + expect(approvals).toBe(1); expect(observations).toBe(1); expect(events).toBe(1); expect(readFileSync(path, "utf8")).toBe(content); + } finally { await service.settled(); db.close(); f.cleanup(); } +}); diff --git a/packages/ui-server/tests/policy-proposal.test.ts b/packages/ui-server/tests/policy-proposal.test.ts index 2b02b3aa6f..56d35b8023 100644 --- a/packages/ui-server/tests/policy-proposal.test.ts +++ b/packages/ui-server/tests/policy-proposal.test.ts @@ -41,25 +41,50 @@ test("approval publishes exact bytes under the shared brain lock and the next ad expect(admitted.policy.profiles.interactive).toBe("governed"); expect(result.sections).toEqual(["profiles.interactive"]); expect(result.bodyChanged).toBe(true); }); -test("the review splits frontmatter where the policy parser ends it (#2507)", async () => { - // Unclosed: the parser reads every line as YAML, so the rules are frontmatter, not body. - const unclosed = "---\nschema_version: 1\nprofiles:\n interactive: strict\n"; - const f = fixture(), pending = f.service.propose(f.turn, "unclosed", { ...input, content: unclosed }); await f.service.settled(); - const review = f.service.read("odysseus", "policy-turn", "unclosed")!; - expect(review.frontmatterDiff).toContain("+ interactive: strict"); expect(review.bodyDiff).not.toContain("interactive"); - await f.answer(false); await pending; - // `---x` closes the block for the parser: the line after it is body, not frontmatter. - const dashed = "---\nschema_version: 1\nprofiles:\n interactive: governed\n---x\nlater: 1\n---\nOdysseus reviews the policy.\n"; - const g = fixture(), second = g.service.propose(g.turn, "dashed", { ...input, content: dashed }); await g.service.settled(); - const split = g.service.read("odysseus", "policy-turn", "dashed")!; - expect(split.frontmatterDiff).not.toContain("later"); expect(split.frontmatterDiff.endsWith("+ ---")).toBe(true); expect(split.bodyDiff).toContain("+ later: 1"); - await g.answer(false); await second; - // Whitespace after the closing dashes: the whole closing line stays frontmatter. - const spaced = proposed.replace("strict\n---\n", "strict\n--- \n"); - const h = fixture(), third = h.service.propose(h.turn, "spaced", { ...input, content: spaced }); await h.service.settled(); - const line = h.service.read("odysseus", "policy-turn", "spaced")!; - expect(line.frontmatterDiff).toContain("+ --- \n+ "); expect(line.bodyDiff).toBe("- Odysseus reviews the policy.\n- \n+ Odysseus approves the policy.\n+ "); - await h.answer(false); await third; +const ambiguousProposals = [ + ["unclosed", "---\nschema_version: 1\nprofiles:\n interactive: strict\n"], + ...["---x", "---yaml", "----"].flatMap(fence => [ + [`opening ${fence}`, proposed.replace(/^---/, fence)], + [`closing ${fence}`, proposed.replace("strict\n---\n", `strict\n${fence}\n`)], + ]), +] as const; +for (const [name, content] of ambiguousProposals) test(`ambiguous proposal ${name} refuses before approval (#3666)`, async () => { + const f = fixture(); + // Settle acceptance too, so removing the guard fails on the rejection assertion without hanging. + f.turn.approve = async () => { throw new Error("APPROVAL_MUST_NOT_BE_REQUESTED"); }; + await expect(f.service.propose(f.turn, "ambiguous", { ...input, content })).rejects.toThrow("Invalid policy"); + expect(f.service.read("odysseus", "policy-turn", "ambiguous")).toBeNull(); + expect(f.db.query("SELECT count(*) AS n FROM policy_proposals").get()).toEqual({ n: 0 }); + expect(f.emitted).toEqual([]); expect(f.edits).toEqual([]); expect(f.events).toEqual([]); + expect(readFileSync(f.path, "utf8")).toBe(original); +}); +for (const [name, content] of [ + ["LF", proposed], + ["trailing spaces and tabs", proposed.replaceAll("---\n", "--- \t\n")], + ["BOM", `\uFEFF${proposed}`], + ["CRLF", proposed.replaceAll("\n", "\r\n")], + ["BOM and spaced CRLF", `\uFEFF${proposed.replaceAll("---\n", "--- \t\n").replaceAll("\n", "\r\n")}`], + ["EOF closing fence", proposed.slice(0, proposed.indexOf("\n---\n") + 4)], +] as const) test(`standalone proposal fences preserve exact ${name} bytes (#3666)`, async () => { + const f = fixture(), pending = f.service.propose(f.turn, "valid", { ...input, content }); + await f.service.settled(); expect(f.count()).toBe(1); + const review = f.service.read("odysseus", "policy-turn", "valid")!; + expect(review.frontmatterDiff).toContain("+ interactive: strict"); + expect(review.bodyDiff).not.toContain("interactive"); + expect(review.frontmatterDiff).not.toContain("Odysseus approves"); + if (content.includes("Odysseus approves")) expect(review.bodyDiff).toContain("+ Odysseus approves the policy."); + await f.answer(true); expect((await pending).state).toBe("updated"); + expect(readFileSync(f.path, "utf8")).toBe(content); expect(f.edits).toEqual([original, content]); expect(f.events).toHaveLength(1); +}); +for (const [name, before] of ambiguousProposals) test(`valid replacement repairs old ${name} with parser-aligned review (#3666)`, async () => { + const f = fixture(); writeFileSync(f.path, before); + const pending = f.service.propose(f.turn, "repair", input); await f.service.settled(); + const review = f.service.read("odysseus", "policy-turn", "repair")!; + // Old delimiters retain the shared parser's split; strictness only applies to new bytes. + if (name.startsWith("opening")) expect(review.frontmatterDiff + review.bodyDiff).toContain(`- ${name.slice(8)}`); + if (name === "unclosed") expect(review.bodyDiff).not.toContain("- interactive: strict"); + if (name === "closing ---x") { expect(review.frontmatterDiff).not.toContain("- x"); expect(review.bodyDiff).toContain("- x"); } + await f.answer(true); expect((await pending).state).toBe("updated"); expect(readFileSync(f.path, "utf8")).toBe(proposed); expect(f.edits).toEqual([before, proposed]); }); test("decline preserves bytes and retains the same request receipt", async () => { const f = fixture(), pending = f.service.propose(f.turn, "policy-1", input); await f.answer(false); @@ -288,3 +313,17 @@ test("an occupied staging name never grants cleanup ownership of a real similarl expect(changes).toHaveLength(1);expect(changes[0]).toMatchObject({path:name,actor:"agent",class:"content"}); expect(journal.version("ithaca","policy-turn",changes[0]!.sequence,"after")!.bytes(1024).toString()).toBe(bytes); }); + +test("publication rechecks strict boundaries after schema validation (#3666)", async () => { + let calls = 0; + const f = fixture({ validate: bytes => { + const result = parseGovernancePolicy(bytes); + // The existing validation seam changes the selected delimiter only on revalidation. + if (++calls === 2) bytes[proposed.indexOf("\n---\n") + 4] = "x".charCodeAt(0); + return result; + } }); + const pending = f.service.propose(f.turn, "revalidate-boundary", input); await f.answer(true); + const result = await pending; + expect(result.state).toBe("invalid"); expect(result.message).toContain("standalone ---"); + expect(readFileSync(f.path, "utf8")).toBe(original); expect(f.edits).toEqual([]); expect(f.events).toEqual([]); +}); From 130ad79490abba8d8877385a35c25a503000d0cd Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Sun, 15 Nov 2026 14:30:55 +0000 Subject: [PATCH 2/2] test(ui-server): retain exact spaced-fence review assertion --- packages/ui-server/tests/policy-proposal.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/ui-server/tests/policy-proposal.test.ts b/packages/ui-server/tests/policy-proposal.test.ts index 56d35b8023..0b0726e5df 100644 --- a/packages/ui-server/tests/policy-proposal.test.ts +++ b/packages/ui-server/tests/policy-proposal.test.ts @@ -72,6 +72,10 @@ for (const [name, content] of [ expect(review.frontmatterDiff).toContain("+ interactive: strict"); expect(review.bodyDiff).not.toContain("interactive"); expect(review.frontmatterDiff).not.toContain("Odysseus approves"); + if (name === "trailing spaces and tabs") { + expect(review.frontmatterDiff).toContain("+ --- \t\n+ "); + expect(review.bodyDiff).toBe("- Odysseus reviews the policy.\n- \n+ Odysseus approves the policy.\n+ "); + } if (content.includes("Odysseus approves")) expect(review.bodyDiff).toContain("+ Odysseus approves the policy."); await f.answer(true); expect((await pending).state).toBe("updated"); expect(readFileSync(f.path, "utf8")).toBe(content); expect(f.edits).toEqual([original, content]); expect(f.events).toHaveLength(1);