From 777c885e6c737bda204c9f4610decf4ecdf0322c Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Thu, 5 Nov 2026 12:32:40 +0000 Subject: [PATCH 1/9] CONTRACT: feat(ui-server): add durable owner trust Settings publication --- .changeset/durable-human-trust-settings.md | 5 + api-report/ui-server.txt | 1 + docs/integration-contract/package-api.md | 48 ++++ .../migrations/080_trust_settings.sql | 22 ++ packages/ui-server/src/app.ts | 10 + .../ui-server/src/brain/policy-proposal.ts | 35 +-- .../ui-server/src/brain/policy-publication.ts | 26 +++ .../src/brain/trust-settings-writes.ts | 25 ++ .../ui-server/src/brain/trust-settings.ts | 220 ++++++++++++++++++ packages/ui-server/src/brain/turn-journal.ts | 6 + .../ui-server/src/routes/trust-settings.ts | 35 +++ .../tests/fixtures/trust-settings-crash.ts | 14 ++ .../ui-server/tests/trust-settings.test.ts | 177 ++++++++++++++ 13 files changed, 596 insertions(+), 28 deletions(-) create mode 100644 .changeset/durable-human-trust-settings.md create mode 100644 packages/ui-server/migrations/080_trust_settings.sql create mode 100644 packages/ui-server/src/brain/policy-publication.ts create mode 100644 packages/ui-server/src/brain/trust-settings-writes.ts create mode 100644 packages/ui-server/src/brain/trust-settings.ts create mode 100644 packages/ui-server/src/routes/trust-settings.ts create mode 100644 packages/ui-server/tests/fixtures/trust-settings-crash.ts create mode 100644 packages/ui-server/tests/trust-settings.test.ts diff --git a/.changeset/durable-human-trust-settings.md b/.changeset/durable-human-trust-settings.md new file mode 100644 index 0000000000..6b1bb33189 --- /dev/null +++ b/.changeset/durable-human-trust-settings.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Add password-owner Settings trust publication with exact-byte reviews, descriptor-bound writes, bounded durable operation receipts and crash-safe readback. Trust enforcement and repository identity acquisition remain unavailable until their independently qualified implementations; saving policy never clears historical taint or grants runtime permission. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 0ac49fe01e..cd307b3d0d 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2447,6 +2447,7 @@ signatures (every public export and the types it is made of) isHeld(): boolean; maintain: () => Promise; observe(): Promise; + observeSettingsPolicy(_operationId: string, approvedWrite: () => void): Promise; observeUserPolicy(turnId: string, approvedWrite: () => Promise | void): Promise; onObservation(observer: (turnId: string, facts: { changedPaths: number; diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index e1f5c995b3..5ca936a62a 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4791,3 +4791,51 @@ reports record this additive type change. Pure canonicalization and matching helpers remain on the existing brain-common internal governance-policy entry point and establish no new extension seam or runtime authority. No SDK safety capability, HTTP endpoint, history DTO or provider conversation changes here. + +### Human trust Settings publication + +The optional owner-only `/api/trust-settings` HTTP surface is a policy-publication +building block. `GET /api/trust-settings` reads the current trust-only revision, +exact policy hash, `origins`, `repositories`, and disabled runtime capabilities. +`POST /api/trust-settings/prepare` accepts strict version-1 JSON with +`expectedTrustRevision`, `expectedPolicyHash` and exactly one `change`: +`{action:create|edit,rule}` or `{action:remove,ruleId}`. The host issues the +request/operation/review IDs and retains exact base/proposed UTF-8 policy text, +reviewed SHA-256 and a 15-minute expiry. A selector change requires remove/add. +Repository creates/edits refuse `repository_identity_unavailable`: browser IDs +are not host identity verification and this surface implements no metadata +transport. Existing repository rules can be read and removed. + +`POST /api/trust-settings/commit` accepts only `{version:1,requestId,reviewId, +reviewedBytesHash}`; `GET /api/trust-settings/:request` only reads that caller's +receipt/review and current policy. Both mutation routes require a present exact +same-origin Origin and JSON, at most 65536 bytes, plus a live password-mode +password/passkey owner. Agent, ambient, voice and body-supplied identity/channel +fields supply no authority. Authority is checked after waits and at publication. + +Receipts bind principal/credential lifetime, served brain, operation, request, +exact base/topology and reviewed hash. Prepared state precedes any write; the +shared privileged publisher syncs staging bytes and the containing directory. +Only a FULL durable proof written after this operation's publication establishes +`publication:proved`. A crash in writing/rename before that proof returns +`unknown`, even if current file bytes match. Retries with identical commit data +only read the original outcome; changed data conflicts. Expired handles can +never create operations. Prepared/readback text survives stale-base refusal. + +The receipt stages are `prepared|file_published|committed|partial|unknown|refused`; +`committed` is an internal publication-completion stage, never proof of live +runtime enforcement. Current responses use `partial` for saved policy because +`enforcement:unavailable` remains truthful until the admission implementation. +`currentRule:present|removed|changed|unknown` is refreshed on reads, independently +of historical publication proof. No removal receipt claims an enforcing fence. +No agent turn, provider message or ordinary governance snapshot is changed. +The live trust projection retains last-valid rules on invalid policy, reports +an error, and increments its decimal uint64 revision only for trust-list changes. +It is supplied for future admission integration; runtime capabilities remain off. + +There are at most 32 outstanding reviews per principal, 256 per brain, 10000 +receipts and 16 MiB reserved payload/receipt storage. New requests fail at +capacity; live receipts are not evicted. Terminal receipts survive at least +24 hours. Unknown writes are never replayed, including after pruning. Settings +migration 080 has no dependency on occurrence-ledger migration 079/081+; the +loader applies each unapplied filename in sorted order on every startup. diff --git a/packages/ui-server/migrations/080_trust_settings.sql b/packages/ui-server/migrations/080_trust_settings.sql new file mode 100644 index 0000000000..6ed2e894f7 --- /dev/null +++ b/packages/ui-server/migrations/080_trust_settings.sql @@ -0,0 +1,22 @@ +-- Independent of occurrence-ledger migrations 079 and 081+; no ledger objects. +CREATE TABLE trust_settings_operations ( + request_id TEXT PRIMARY KEY, + brain_id TEXT NOT NULL, + principal_id TEXT NOT NULL, + authority TEXT NOT NULL, + expires_at INTEGER NOT NULL, + retain_until INTEGER NOT NULL, + payload TEXT NOT NULL, + payload_bytes INTEGER NOT NULL, + stage TEXT NOT NULL, + proof TEXT, + receipt TEXT NOT NULL +); +CREATE INDEX trust_settings_owner ON trust_settings_operations(brain_id, principal_id); +CREATE TABLE trust_settings_projection ( + brain_id TEXT PRIMARY KEY, + revision TEXT NOT NULL, + rules TEXT NOT NULL, + policy_hash TEXT, + error TEXT +); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index ef98c0f66b..83ed6db075 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1,3 +1,5 @@ +import { createTrustSettings } from "./brain/trust-settings.js"; +import { createTrustSettingsRoutes } from "./routes/trust-settings.js"; import { isWithin } from "@schlessera/brain-common/internal/safe-path"; import { STORAGE_SETTLEMENT_MS } from "./db/settlement.js"; import { guardSqliteCleanup } from "./db/write-worker.js"; @@ -1188,6 +1190,14 @@ export async function createApp(options: CreateAppOptions = {}): Promise { + if (authMode !== "password") return null; + const p = resolvePrincipal(db, id); + return p?.kind === "owner" && ["password", "passkey"].includes(p.authMethod) && isUsablePrincipal(p, Date.now()) + ? JSON.stringify([p.id, p.authMethod, p.credentialId, p.createdAt, p.expiresAt]) : null; + }, observe: (id, publish) => journal.observeSettingsPolicy(id, publish) }); + app.route("/api", createTrustSettingsRoutes({ settings: trustSettings, trustProxy: auth.trustProxy })); const apifyOwner = (id: string) => { const principal = resolvePrincipal(db, id); return !!principal && ["owner", "ambient"].includes(principal.kind) && isUsablePrincipal(principal, Date.now()); }; // Settings edits (#3163) go through the existing policy proposals, the only policy writer, in a user journal window. const apifyEdits = createApifyPolicyEdits({ root: config.brainPath, proposals: policyProposals, journal, authorized: apifyOwner }); diff --git a/packages/ui-server/src/brain/policy-proposal.ts b/packages/ui-server/src/brain/policy-proposal.ts index dbf52281ed..0cf7a81b2e 100644 --- a/packages/ui-server/src/brain/policy-proposal.ts +++ b/packages/ui-server/src/brain/policy-proposal.ts @@ -1,5 +1,6 @@ /** The only privileged policy writer. Worker input is never approval authority. */ -import { closeSync, constants, fchmodSync, fsyncSync, linkSync, openSync, realpathSync, renameSync, rmdirSync, unlinkSync, writeFileSync } from "node:fs"; +import { realpathSync, rmdirSync } from "node:fs"; +import { publishProtectedPolicy } from "./policy-publication.js"; import { createHash } from "node:crypto"; import type { SessionHistoryMessage } from "@schlessera/brain-ui-sdk/protocol"; import type { Database } from "bun:sqlite"; @@ -179,7 +180,7 @@ export function createPolicyProposals(options: { const currentValidation = validate(bytes); if (!currentValidation.ok || currentValidation.status !== "valid") throw new Refusal("invalid", `This proposal no longer passes validation: ${currentValidation.errors.join("; ")}. Nothing was written. A fresh proposal is required.`); const created: string[] = []; - let target: Target | undefined, temp: string | undefined, unpublished = false; + let target: Target | undefined, unpublished = false; try { target = open(root, review.baseHash === null, created); verify(target, review.baseHash); options.beforeCommit?.(); authority(); verify(target, review.baseHash); @@ -193,31 +194,10 @@ export function createPolicyProposals(options: { // The operation owns the staging inode for this synchronous // callback only. Both journal observations are outside its // lifetime; no path/prefix ignore can hide real worker files. - const staging = `/proc/self/fd/${target!.directories.at(-1)!.fd}/.brain-policy-${crypto.randomUUID()}`; - let publicationFailed = false, publicationError: unknown; - try { - const fd = openSync(staging, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, target!.mode ?? 0o644); - temp = staging; // Only a successfully created inode belongs to this operation. - try { writeFileSync(fd, bytes); if (target!.mode !== undefined) fchmodSync(fd, target!.mode); fsyncSync(fd); } finally { closeSync(fd); } - if (held()) unpublished = true; - else { - authority(false); verify(target!, review.baseHash); - if (review.baseHash === null) linkSync(temp, target!.at); else renameSync(temp, target!.at); - committed = true; - } - } catch (error) { publicationFailed = true; publicationError = error; } - // First publication uses link rather than an overwriting - // rename; unlink its remaining name before observation. - if (temp) { - try { unlinkSync(temp); temp = undefined; } - catch (error) { - if ((error as NodeJS.ErrnoException).code === "ENOENT") temp = undefined; - else { if (!publicationFailed) publicationError = error; publicationFailed = true; } - } - } - if (publicationFailed) throw publicationError; - if (unpublished) return; - fsyncSync(target!.directories.at(-1)!.fd); + publishProtectedPolicy(target!, bytes, review.baseHash, () => { + if (held()) throw new AuthorityHeld(); + authority(false); verify(target!, review.baseHash); + }, () => { committed = true; }); }); // Nothing was published and the observation, its hold and (on // unwinding) the lock are released: wait out the pause and retry. @@ -225,7 +205,6 @@ export function createPolicyProposals(options: { review.state = "updated"; review.message = "Policy updated. Applies from the next turn."; await options.recordEvent(review, turn); } finally { - if (temp) { try { unlinkSync(temp); } catch { /* Rename consumed it. */ } } if (target) close(target); if (!committed) for (const directory of created.reverse()) { try { rmdirSync(directory); } catch { /* Preserve concurrent files. */ } } } diff --git a/packages/ui-server/src/brain/policy-publication.ts b/packages/ui-server/src/brain/policy-publication.ts new file mode 100644 index 0000000000..499f253c9b --- /dev/null +++ b/packages/ui-server/src/brain/policy-publication.ts @@ -0,0 +1,26 @@ +/** Shared descriptor-bound privileged file publisher. Callers own the brain lock, + * observation window and durable operation/turn identity. Never exported to workers. */ +import { closeSync, constants, fchmodSync, fsyncSync, linkSync, openSync, renameSync, unlinkSync, writeFileSync } from "node:fs"; +import { verifyGovernancePolicyAnchored, type AnchoredGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; + +export function publishProtectedPolicy(target: AnchoredGovernancePolicy, bytes: Uint8Array, baseHash: string | null, + check: () => void, published: () => void): void { + let temp: string | undefined; + try { + check(); verifyGovernancePolicyAnchored(target, baseHash); + const staging = `/proc/self/fd/${target.directories.at(-1)!.fd}/.brain-policy-${crypto.randomUUID()}`; + const fd = openSync(staging, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, target.mode ?? 0o644); + temp = staging; + try { writeFileSync(fd, bytes); if (target.mode !== undefined) fchmodSync(fd, target.mode); fsyncSync(fd); } + finally { closeSync(fd); } + // No await between the last authority/topology/base check and the atomic publication. + check(); verifyGovernancePolicyAnchored(target, baseHash); + if (baseHash === null) linkSync(temp, target.at); else renameSync(temp, target.at); + published(); + try { unlinkSync(temp); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } + temp = undefined; + // Include newly created ancestors: a durable name in the leaf alone does + // not make its parent names durable after a power loss. + for (const directory of [...target.directories].reverse()) fsyncSync(directory.fd); + } finally { if (temp) { try { unlinkSync(temp); } catch { /* Only our staging name. */ } } } +} diff --git a/packages/ui-server/src/brain/trust-settings-writes.ts b/packages/ui-server/src/brain/trust-settings-writes.ts new file mode 100644 index 0000000000..87212a29c4 --- /dev/null +++ b/packages/ui-server/src/brain/trust-settings-writes.ts @@ -0,0 +1,25 @@ +/** FULL write-worker commits for Settings identities and operation-bound publication proofs. */ +import type { Database } from "bun:sqlite"; +import type { WriteProcedures } from "../db/write-worker.js"; +export const url = import.meta.url; +export function setup(db: Database): WriteProcedures { + return { + insert(row: { requestId: string; brainId: string; principalId: string; authority: string; expires: number; retain: number; payload: string; receipt: string }, now: number) { + return db.transaction(() => { + db.query("DELETE FROM trust_settings_operations WHERE retain_until < ?").run(now); + const total = db.query("SELECT count(*) n, coalesce(sum(payload_bytes + 16384),0) bytes FROM trust_settings_operations").get() as { n: number; bytes: number }; + const pending = db.query("SELECT count(*) n, coalesce(sum(principal_id = ?),0) own FROM trust_settings_operations WHERE brain_id = ? AND stage = 'prepared' AND expires_at >= ?").get(row.principalId, row.brainId, now) as { n: number; own: number }; + // Reserve terminal/proof capacity for every admitted request, never evict live receipts. + if (total.n >= 10000 || total.bytes + Buffer.byteLength(row.payload) + 16384 > 16777216 || pending.n >= 256 || pending.own >= 32) return "capacity"; + db.query("INSERT INTO trust_settings_operations VALUES (?,?,?,?,?,?,?,?,? ,NULL,?)").run(row.requestId, row.brainId, row.principalId, row.authority, row.expires, row.retain, row.payload, Buffer.byteLength(row.payload), "prepared", row.receipt); + return "prepared"; + }).immediate(); + }, + stage(id: string, stage: string, receipt: string, proof: string | null, now: number) { + db.query("UPDATE trust_settings_operations SET stage=?, receipt=?, proof=coalesce(?,proof), retain_until=max(retain_until,?) WHERE request_id=?").run(stage, receipt, proof, now + 86400000, id); + }, + projection(brain: string, revision: string, rules: string, hash: string | null, error: string | null) { + db.query("INSERT INTO trust_settings_projection VALUES (?,?,?,?,?) ON CONFLICT(brain_id) DO UPDATE SET revision=excluded.revision,rules=excluded.rules,policy_hash=excluded.policy_hash,error=excluded.error").run(brain, revision, rules, hash, error); + }, + }; +} diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts new file mode 100644 index 0000000000..42d35d2938 --- /dev/null +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -0,0 +1,220 @@ +/** Human Settings operations. Markdown is authoritative; these rows are bounded + * request/audit receipts, never a second policy source or an agent turn. */ +import { createHash, randomBytes } from "node:crypto"; +import { lstatSync, realpathSync, rmdirSync } from "node:fs"; +import { resolve, join } from "node:path"; +import type { Database } from "bun:sqlite"; +import { z } from "zod"; +import { parseFrontmatter } from "@schlessera/brain-common/internal/frontmatter"; +import { openGovernancePolicyAnchored, verifyGovernancePolicyAnchored, parseGovernancePolicy, TrustedSourcesSchema, TrustRuleSchema, + TRUST_RUNTIME_CAPABILITIES, type TrustRule, type AnchoredGovernancePolicy } from "@schlessera/brain-common/internal/governance-policy"; +import { BRAIN_LOCK_KEY, type KeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { procedureCaller, type SqliteWriter } from "../db/write-worker.js"; +import { publishProtectedPolicy } from "./policy-publication.js"; +import * as writes from "./trust-settings-writes.js"; +const hash = (s: string | Uint8Array) => createHash("sha256").update(s).digest("hex"); +const id = () => randomBytes(24).toString("base64url"); +const exactDiff = (before: string | null, after: string) => (before ?? "").split("\n").map(line => `- ${line}`).concat(after.split("\n").map(line => `+ ${line}`)).join("\n"); +const digest = z.string().regex(/^[a-f0-9]{64}$/u); +const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u); +const ruleId = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/u); +const TrustPrepareSchema = z.strictObject({ version: z.literal(1), expectedTrustRevision: revision, + expectedPolicyHash: digest.nullable(), change: z.discriminatedUnion("action", [ + z.strictObject({ action: z.literal("create"), rule: TrustRuleSchema }), + z.strictObject({ action: z.literal("edit"), rule: TrustRuleSchema }), + z.strictObject({ action: z.literal("remove"), ruleId }), + ]) }); +const TrustCommitSchema = z.strictObject({ version: z.literal(1), requestId: ruleId, reviewId: ruleId, reviewedBytesHash: digest }); +type Prepare = z.output; +type Commit = z.output; +export class TrustSettingsError extends Error { + constructor(readonly code: string, readonly status: 400 | 403 | 404 | 409 | 503 = 409) { super(code); } +} +interface Projection { revision: string; rules: TrustRule[]; policyHash: string | null; error: string | null } +interface Receipt { + version: 1; requestId: string; operationId: string; stage: "prepared" | "file_published" | "committed" | "partial" | "unknown" | "refused"; + publication: "not_published" | "proved" | "unknown"; ruleId: string; publishedTrustRevision: string | null; + currentRule: "present" | "removed" | "changed" | "unknown"; enforcement: "unavailable"; reason: string | null; +} +interface Payload { input: Prepare; reviewId: string; proposed: string; proposedHash: string; base: string | null; topology: string; rule: TrustRule | null } +interface Row { principal_id: string; brain_id: string; authority: string; expires_at: number; retain_until: number; payload: string; stage: string; proof: string | null; receipt: string } +const topology = (root: string) => [root, join(root, "context"), join(root, "context/policies"), join(root, "context/policies/governance.md")].map((path, i) => { + const stat = lstatSync(path, { throwIfNoEntry: false }); + if (!stat) return null; + if (i < 3 && !stat.isDirectory()) throw new TrustSettingsError("stale_base"); + return i < 3 ? [stat.dev, stat.ino] : [stat.dev, stat.ino, stat.ctimeMs]; +}); +const matchesTopology = (root: string, expected: string, created: boolean) => { + const a = JSON.parse(expected) as unknown[], b = topology(root); + return a.every((entry, i) => created && i < 3 && entry === null || JSON.stringify(entry) === JSON.stringify(b[i])); +}; +/** Only the taint block changes. Parse-back equality refuses aliases, merge keys + * or exotic layouts that would alter any unrelated setting. Review shows exact bytes. */ +function edit(text: string | null, rules: TrustRule[]): string { + const before = text ?? "---\nschema_version: 1\n---\n"; + const m = /^(\uFEFF?---[ \t]*\r?\n)([\s\S]*?\r?\n)?((?:---|\.\.\.)[ \t]*(?:\r?\n|$))/u.exec(before); + if (!m) throw new TrustSettingsError("unsupported_layout"); + const data = parseFrontmatter(before, { dataOnly: true }).data; + const taint = { ...data.taint, trusted_sources: rules }; + const lines = (m[2] ?? "").split(/\r?\n/u); if (lines.at(-1) === "") lines.pop(); + const start = lines.findIndex(line => /^taint[ \t]*:/u.test(line)); + const block = `taint: ${JSON.stringify(taint)}`; + if (start < 0) lines.push(block); + else { let end = start + 1; while (end < lines.length && !/^[^\s#]/u.test(lines[end]!)) end++; + while (end > start + 1 && /^\s*(?:#.*)?$/u.test(lines[end - 1]!)) end--; + lines.splice(start, end - start, block); } + const newline = before.includes("\r\n") ? "\r\n" : "\n"; + const after = m[1] + lines.join(newline) + newline + m[3] + before.slice(m[0].length); + const expected = { ...data, taint }; + if (JSON.stringify(parseFrontmatter(after, { dataOnly: true }).data) !== JSON.stringify(expected) || !parseGovernancePolicy(Buffer.from(after)).ok) + throw new TrustSettingsError("unsupported_layout"); + return after; +} +export function createTrustSettings(options: { + root: string; db: Database; writer?: SqliteWriter; lock: Pick; + /** Null unless the current password-mode human principal remains usable. The + * fingerprint includes credential/lifetime identity, never a body/channel claim. */ + authority(principalId: string): string | null; + observe(operationId: string, publish: () => void): Promise; + now?: () => number; + /** Host-only deterministic crash/race injection, never wired from HTTP. */ + checkpoint?(stage: string): void | Promise; +}) { + let root: string; + try { root = realpathSync(options.root); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; root = resolve(options.root); } + const brain = hash(root); + const call = procedureCaller(options.db, writes, undefined, options.writer), now = options.now ?? Date.now; + const authority = (principal: string, expected?: string) => { + const value = options.authority(principal); + if (!value || (expected !== undefined && expected !== value)) throw new TrustSettingsError("unauthorized", 403); + return value; + }; + const projection = (): Projection => { + const row = options.db.query("SELECT * FROM trust_settings_projection WHERE brain_id=?").get(brain) as { revision: string; rules: string; policy_hash: string | null; error: string | null } | null; + return row ? { revision: row.revision, rules: JSON.parse(row.rules), policyHash: row.policy_hash, error: row.error } : { revision: "0", rules: [], policyHash: null, error: null }; + }; + const refresh = async (): Promise => { + const old = projection(); let target: AnchoredGovernancePolicy | undefined; + let rules: TrustRule[], policyHash: string | null; + try { + target = openGovernancePolicyAnchored(root); + policyHash = target.bytes === null ? null : hash(target.bytes); verifyGovernancePolicyAnchored(target, policyHash); + const checked = target.bytes === null ? null : parseGovernancePolicy(target.bytes); + if (checked && !checked.ok) throw new Error("invalid"); + rules = checked?.effective.taint.trusted_sources ?? []; + } catch (error) { + if ((error as NodeJS.ErrnoException).code === "ENOENT") { rules = []; policyHash = null; } + else { await call("projection", brain, old.revision, JSON.stringify(old.rules), old.policyHash, "policy_unavailable"); return { ...old, error: "policy_unavailable" }; } + } finally { target?.close(); } + const changed = JSON.stringify(old.rules) !== JSON.stringify(rules); + if (changed && BigInt(old.revision) === 18446744073709551615n) throw new TrustSettingsError("capacity", 503); + const next = { revision: changed ? String(BigInt(old.revision) + 1n) : old.revision, rules, policyHash, error: null }; + await call("projection", brain, next.revision, JSON.stringify(rules), policyHash, null); return next; + }; + const row = (principal: string, request: string): Row => { + authority(principal); + const r = options.db.query("SELECT * FROM trust_settings_operations WHERE request_id=? AND brain_id=? AND principal_id=?").get(request, brain, principal) as Row | null; + if (!r || r.retain_until < now()) throw new TrustSettingsError("unavailable", 404); + authority(principal, r.authority); return r; + }; + const current = (receipt: Receipt, payload: Payload, p: Projection): Receipt => { + const rule = p.rules.find(rule => rule.id === receipt.ruleId); + return { ...receipt, currentRule: p.error ? "unknown" : !rule ? "removed" : JSON.stringify(rule) === JSON.stringify(payload.rule) ? "present" : "changed" }; + }; + const read = async (principal: string, request: string) => { + const r = row(principal, request), payload = JSON.parse(r.payload) as Payload; + let receipt = JSON.parse(r.receipt) as Receipt; + if (r.stage === "writing") receipt = { ...receipt, stage: "unknown", publication: "unknown", reason: "publication_completion_unknown" }; + if (r.stage === "file_published") receipt = { ...receipt, stage: "partial", publication: r.proof ? "proved" : "unknown", reason: "publication_recorded_completion_incomplete" }; + const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); row(principal, request); + return { receipt: current(receipt, payload, p), review: { reviewId: payload.reviewId, base: payload.base, proposed: payload.proposed, + diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at }, policy: p, capabilities: TRUST_RUNTIME_CAPABILITIES }; + }; + return { + /** Live trust-only projection for future admissions. Ordinary policy snapshots + * remain owned by their admitted turn; this never mutates them. */ + async snapshot() { return options.lock.withLock(BRAIN_LOCK_KEY, refresh); }, + async list(principal: string) { authority(principal); const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); authority(principal); + return { ...p, origins: p.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: p.rules.filter(r => r.selector.kind.startsWith("github_")), capabilities: TRUST_RUNTIME_CAPABILITIES }; }, + read, + async prepare(principal: string, raw: unknown) { + const auth = authority(principal), input = TrustPrepareSchema.parse(raw); + if (process.platform !== "linux") throw new TrustSettingsError("unavailable", 503); + // Names/IDs supplied by browsers cannot create repository identity proof. + // Removal remains possible even while repository qualification is unavailable. + if (input.change.action !== "remove" && input.change.rule.selector.kind.startsWith("github_")) throw new TrustSettingsError("repository_identity_unavailable", 503); + const request = await options.lock.withLock(BRAIN_LOCK_KEY, async () => { + authority(principal, auth); const p = await refresh(); authority(principal, auth); + if (p.error) throw new TrustSettingsError("unavailable", 503); + if (p.revision !== input.expectedTrustRevision) throw new TrustSettingsError("stale_revision"); + if (p.policyHash !== input.expectedPolicyHash) throw new TrustSettingsError("stale_base"); + const change = input.change, ruleId = change.action === "remove" ? change.ruleId : change.rule.id; + const existing = p.rules.find(rule => rule.id === ruleId); + if ((change.action === "create") === !!existing) throw new TrustSettingsError("request_conflict"); + if (change.action === "edit" && JSON.stringify(existing!.selector) !== JSON.stringify(change.rule.selector)) throw new TrustSettingsError("target_requires_remove_add"); + if (change.action === "edit" && JSON.stringify(existing) === JSON.stringify(change.rule)) throw new TrustSettingsError("request_conflict"); + const rules = TrustedSourcesSchema.parse(change.action === "create" ? [...p.rules, change.rule] : change.action === "remove" ? p.rules.filter(r => r.id !== ruleId) : p.rules.map(r => r.id === ruleId ? change.rule : r)); + let target: AnchoredGovernancePolicy | undefined; let base: string | null = null; const identity = JSON.stringify(topology(root)); + try { target = openGovernancePolicyAnchored(root); verifyGovernancePolicyAnchored(target, p.policyHash); base = target.bytes?.toString("utf8") ?? null; } + catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT" || p.policyHash !== null) throw error; } + finally { target?.close(); } + const proposed = edit(base, rules), requestId = id(), operationId = id(); + if (Buffer.byteLength(JSON.stringify({ base, proposed, diff: exactDiff(base, proposed) })) > 196608) throw new TrustSettingsError("capacity", 503); + const payload: Payload = { input, reviewId: id(), proposed, proposedHash: hash(proposed), base, topology: identity, rule: change.action === "remove" ? null : change.rule }; + const receipt: Receipt = { version: 1, requestId, operationId, stage: "prepared", publication: "not_published", ruleId, + publishedTrustRevision: null, currentRule: "unknown", enforcement: "unavailable", reason: null }; + const inserted = await call("insert", { requestId, brainId: brain, principalId: principal, authority: auth, expires: now() + 900000, retain: now() + 86400000, + payload: JSON.stringify(payload), receipt: JSON.stringify(receipt) }, now()); + if (inserted === "capacity") throw new TrustSettingsError("capacity", 503); + await options.checkpoint?.("prepared"); return requestId; + }); + return read(principal, request); + }, + async commit(principal: string, raw: unknown) { + const input: Commit = TrustCommitSchema.parse(raw); row(principal, input.requestId); + await options.lock.withLock(BRAIN_LOCK_KEY, async () => { + const r = row(principal, input.requestId), payload = JSON.parse(r.payload) as Payload; + if (payload.reviewId !== input.reviewId || payload.proposedHash !== input.reviewedBytesHash) throw new TrustSettingsError("request_conflict"); + if (r.stage !== "prepared") return; // Readback only, including uncertain writes. + if (r.expires_at < now()) throw new TrustSettingsError("request_expired"); + const receipt = JSON.parse(r.receipt) as Receipt; + let published = false, proved = false; const created: string[] = []; let target: AnchoredGovernancePolicy | undefined; + const save = (stage: string, proof: string | null = null) => call("stage", input.requestId, stage, JSON.stringify(receipt), proof, now()); + try { + const p = await refresh(); row(principal, input.requestId); + if (p.error || p.revision !== payload.input.expectedTrustRevision) throw new TrustSettingsError("stale_revision"); + if (p.policyHash !== payload.input.expectedPolicyHash) throw new TrustSettingsError("stale_base"); + await save("writing"); await options.checkpoint?.("writing"); + if (!matchesTopology(root, payload.topology, false)) throw new TrustSettingsError("stale_base"); + target = openGovernancePolicyAnchored(root, { create: p.policyHash === null, created }); + const check = () => { row(principal, input.requestId); if (r.expires_at < now()) throw new TrustSettingsError("request_expired"); + if (!matchesTopology(root, payload.topology, true)) throw new TrustSettingsError("stale_base"); + verifyGovernancePolicyAnchored(target!, p.policyHash); }; + await options.observe(receipt.operationId, () => { + publishProtectedPolicy(target!, Buffer.from(payload.proposed), p.policyHash, check, () => { published = true; }); + }); + await options.checkpoint?.("renamed"); + // The proof is written only after THIS invocation's atomic publication + // and directory fsync, never inferred by comparing current bytes. + receipt.stage = "file_published"; receipt.publication = "proved"; + receipt.publishedTrustRevision = String(BigInt(p.revision) + 1n); + await save("file_published", JSON.stringify({ operationId: receipt.operationId, principal, brain, authority: r.authority, + baseHash: p.policyHash, expectedTrustRevision: p.revision, publishedTrustRevision: receipt.publishedTrustRevision, reviewedBytesHash: payload.proposedHash })); proved = true; + await options.checkpoint?.("file_published"); + const latest = await refresh(); row(principal, input.requestId); + if (latest.policyHash === payload.proposedHash) receipt.publishedTrustRevision = latest.revision; + // No runtime source/recipient enforcement exists in this slice (#3609). + receipt.stage = "partial"; receipt.reason = "policy_saved_runtime_enforcement_unavailable"; + await save("committed"); await options.checkpoint?.("committed"); + } catch (error) { + receipt.stage = proved ? "partial" : published ? "unknown" : "refused"; + receipt.publication = proved ? "proved" : published ? "unknown" : "not_published"; + receipt.reason = error instanceof TrustSettingsError ? error.code : published ? "recording_failed" : "publication_failed"; + await save(receipt.stage); + } finally { target?.close(); if (!published) for (const path of created.reverse()) { try { rmdirSync(path); } catch { /* Concurrent content remains. */ } } } + }); + return read(principal, input.requestId); + }, + }; +} +export type TrustSettings = ReturnType; diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index 254ac7ce58..0472ee6f19 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -593,6 +593,12 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { const turn=active.get(turnId); if(!turn)throw new JournalStorageUnavailable("history coverage requires an active observation window"); turn.policy.cover(paths); }, + /** Host Settings audit identity is retained by its durable operation store. + * Observe user policy changes across existing turns without minting a turn. */ + observeSettingsPolicy(_operationId: string, approvedWrite: () => void): Promise { return held(async () => { + await observe(); + try { approvedWrite(); } finally { await observe(true); } + }); }, /** The caller retains approval/current-principal authority; this never revives a completed turn. */ observeUserPolicy(turnId: string, approvedWrite: () => void | Promise): Promise { return held(async () => { if (!active.has(turnId) || summary(turnId).state !== "recording") throw new JournalStorageUnavailable("approved policy write requires an active complete observation window"); diff --git a/packages/ui-server/src/routes/trust-settings.ts b/packages/ui-server/src/routes/trust-settings.ts new file mode 100644 index 0000000000..30c2437021 --- /dev/null +++ b/packages/ui-server/src/routes/trust-settings.ts @@ -0,0 +1,35 @@ +/** Password-owner browser boundary; no model, voice or body-supplied authority. */ +import { Hono } from "hono"; +import { ZodError } from "zod"; +import type { AppEnv } from "../app-env.js"; +import { requireJson } from "../middleware/origin.js"; +import { readJsonBody } from "../middleware/body-limit.js"; +import { TrustSettingsError, type TrustSettings } from "../brain/trust-settings.js"; +export function createTrustSettingsRoutes(deps: { settings: TrustSettings; trustProxy: boolean }) { + const routes = new Hono(); + routes.use("/trust-settings*", async (c, next) => { + c.header("Cache-Control", "private, no-store"); + if (!c.get("principal")) return c.json({ code: "unauthorized", reason: "Authentication required", retryable: false }, 401); + if (c.req.method !== "GET") { + // Require the actual Origin, independent of spoofed fetch metadata and + // the broader legacy API allowlist. Reverse-proxy TLS uses trusted proto. + let expected: string; + try { + const proto = deps.trustProxy ? c.req.header("x-forwarded-proto")?.split(",")[0]?.trim() : undefined; + expected = new URL(`${proto ? `${proto}:` : new URL(c.req.url).protocol}//${c.req.header("host") ?? new URL(c.req.url).host}`).origin; + } catch { return c.json({ code: "unauthorized", reason: "Same-origin request required", retryable: false }, 403); } + if (c.req.header("origin") !== expected) return c.json({ code: "unauthorized", reason: "Same-origin request required", retryable: false }, 403); + } + await next(); + }); + routes.onError((error, c) => error instanceof TrustSettingsError ? c.json({ code: error.code, reason: error.message, retryable: false }, error.status) + : error instanceof ZodError ? c.json({ code: "request_conflict", reason: "Invalid request", retryable: false }, 400) + : c.json({ code: "unavailable", reason: "Settings unavailable", retryable: false }, 503)); + routes.get("/trust-settings", async c => c.json(await deps.settings.list(c.get("principal")!.id))); + routes.get("/trust-settings/:request", async c => c.json(await deps.settings.read(c.get("principal")!.id, c.req.param("request")))); + for (const action of ["prepare", "commit"] as const) routes.post(`/trust-settings/${action}`, requireJson(), async c => { + const body = await readJsonBody(c, 65536).catch(() => null); if (body instanceof Response) return body; + return c.json(await deps.settings[action](c.get("principal")!.id, body)); + }); + return routes; +} diff --git a/packages/ui-server/tests/fixtures/trust-settings-crash.ts b/packages/ui-server/tests/fixtures/trust-settings-crash.ts new file mode 100644 index 0000000000..98230da840 --- /dev/null +++ b/packages/ui-server/tests/fixtures/trust-settings-crash.ts @@ -0,0 +1,14 @@ +/** Process-death fixture: durable worker writes, real descriptors and publication. */ +import { join } from "node:path"; +import { createUiDb } from "../../src/db/client.js"; +import { openSqliteWriter } from "../../src/db/write-worker.js"; +import { createTrustSettings } from "../../src/brain/trust-settings.js"; +import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +const [root, at, request] = process.argv.slice(2) as [string, string, string]; +const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); +const settings = createTrustSettings({ root, db, writer, lock: createKeyedLock(), authority: () => "owner-epoch", + observe: async (_id, publish) => publish(), checkpoint: stage => { if (stage === at) process.exit(77); } }); +const review = JSON.parse(await Bun.file(join(root, "request.json")).text()); +if (at === "prepared") await settings.prepare("odysseus", review.input); +else await settings.commit("odysseus", { version: 1, requestId: request, reviewId: review.reviewId, reviewedBytesHash: review.reviewedBytesHash }); +await writer.close(); db.close(); diff --git a/packages/ui-server/tests/trust-settings.test.ts b/packages/ui-server/tests/trust-settings.test.ts new file mode 100644 index 0000000000..860e701541 --- /dev/null +++ b/packages/ui-server/tests/trust-settings.test.ts @@ -0,0 +1,177 @@ +import { createGovernancePolicyReader } from "../src/brain/governance-policy.js"; +import { createTurnJournal } from "../src/brain/turn-journal.js"; +import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; +import { afterEach, expect, test } from "bun:test"; +import { mkdtempSync, mkdirSync, readFileSync, writeFileSync, rmSync, renameSync, symlinkSync, openSync, closeSync, constants } from "node:fs"; +import { join } from "node:path"; +import { createHash } from "node:crypto"; +import { Hono } from "hono"; +import { createKeyedLock, BRAIN_LOCK_KEY } from "@schlessera/brain-ui-sdk/server"; +import { createTrustSettings } from "../src/brain/trust-settings.js"; +import { createTrustSettingsRoutes } from "../src/routes/trust-settings.js"; +import { createUiDb } from "../src/db/client.js"; +import { openSqliteWriter } from "../src/db/write-worker.js"; +import { authGuard, authRoutes, type AuthRuntime } from "../src/middleware/auth.js"; +import { resolveServerConfig } from "../src/config/env.js"; +import { resolvePrincipal, isUsablePrincipal } from "../src/db/principals.js"; +import type { AppEnv } from "../src/app-env.js"; +const cleanup: (() => void | Promise)[] = []; +afterEach(async () => { for (const f of cleanup.splice(0).reverse()) await f(); }); +const initial = "---\nschema_version: 1\n# Keep ordinary configuration\nprofiles: {interactive: governed}\nbudgets: {turn: {block_usd: 17}}\n---\nThe voyage policy.\n"; +const rule = { id: "ithaca", label: "Ithaca", incomingContent: true, recipientWhileRestricted: false, + selector: { kind: "web_origin" as const, scheme: "https" as const, host: "example.org", port: 443 } }; +const hash = (text: string) => createHash("sha256").update(text).digest("hex"); +async function fixture(patch: Partial[0]> = {}) { + const scratch = join(import.meta.dir, "../../../tmp/trust-settings-tests"); mkdirSync(scratch, { recursive: true }); + const root = mkdtempSync(join(scratch, "case-")); cleanup.push(() => rmSync(root, { recursive: true, force: true })); + mkdirSync(join(root, "context/policies"), { recursive: true }); const path = join(root, "context/policies/governance.md"); writeFileSync(path, initial); + const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); cleanup.push(async () => { await writer.close(); db.close(); }); + const lock = createKeyedLock(); let auth: string | null = "owner-epoch"; const observations: string[] = []; + const options = { root, db, writer, lock, authority: (id: string) => id === "odysseus" ? auth : null, + observe: async (id: string, publish: () => void) => { observations.push(id); publish(); }, ...patch }; + const settings = createTrustSettings(options); + const prepare = async (change: unknown = { action: "create", rule }) => { const p = await settings.list("odysseus"); + return settings.prepare("odysseus", { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change }); }; + const commit = (p: Awaited>, change = {}) => settings.commit("odysseus", { version: 1, requestId: p.receipt.requestId, + reviewId: p.review.reviewId, reviewedBytesHash: p.review.reviewedBytesHash, ...change }); + return { root, path, db, writer, lock, settings, options, prepare, commit, observations, revoke: () => { auth = null; } }; +} +test("real descriptor CRUD is exact, durable and creates no agent turn; readback reflects another device removal", async () => { + const f = await fixture(), draft = await f.prepare(); + expect(draft.review.base).toBe(initial); expect(draft.review.proposed).toContain("# Keep ordinary configuration"); + const saved = await f.commit(draft); expect(saved.receipt.publication).toBe("proved"); expect(saved.receipt.enforcement).toBe("unavailable"); + expect(saved.receipt.currentRule).toBe("present"); expect(readFileSync(f.path, "utf8")).toBe(draft.review.proposed); + const edit = await f.prepare({ action: "edit", rule: { ...rule, label: "The home harbor", recipientWhileRestricted: true } }); await f.commit(edit); + expect((await f.settings.list("odysseus")).origins[0]!.recipientWhileRestricted).toBe(true); + const remove = await f.prepare({ action: "remove", ruleId: rule.id }); await f.commit(remove); + expect((await f.settings.read("odysseus", draft.receipt.requestId)).receipt.currentRule).toBe("removed"); + expect((await f.commit(draft)).receipt.currentRule).toBe("removed"); expect(f.observations).toHaveLength(3); + expect(f.db.query("SELECT count(*) n FROM sessions").get()).toEqual({ n: 0 }); + expect(f.db.query("SELECT count(*) n FROM policy_proposals").get()).toEqual({ n: 0 }); + expect((await f.settings.list("odysseus")).capabilities.repositoryRules).toBe(false); +}); +test("changed request, foreign principal, arbitrary handles and expired reviews cannot replay", async () => { + let now = 1000; const f = await fixture({ now: () => now }), draft = await f.prepare(); + await expect(f.commit(draft, { reviewedBytesHash: "a".repeat(64) })).rejects.toThrow("request_conflict"); + await expect(f.settings.read("telemachus", draft.receipt.requestId)).rejects.toThrow("unauthorized"); + await expect(f.commit(draft, { requestId: "forged" })).rejects.toThrow("unavailable"); + now += 900001; await expect(f.commit(draft)).rejects.toThrow("request_expired"); + expect((await f.settings.read("odysseus", draft.receipt.requestId)).review.proposed).toBe(draft.review.proposed); + expect(readFileSync(f.path, "utf8")).toBe(initial); +}); +for (const race of ["bytes", "symlink", "ancestor", "inode", "revoke"] as const) test(`last publication check refuses ${race} after an async observation wait`, async () => { + let mutate = () => {}; const f = await fixture({ observe: async (_id, publish) => { await Promise.resolve(); mutate(); publish(); } }); + const draft = await f.prepare(); let held: number | undefined; + mutate = () => { + if (race === "revoke") f.revoke(); + else if (race === "bytes") writeFileSync(f.path, initial + "Other tab.\n"); + else if (race === "ancestor") { renameSync(join(f.root, "context"), join(f.root, "previous")); symlinkSync(join(f.root, "previous"), join(f.root, "context")); } + else { held = openSync(f.path, constants.O_RDONLY); renameSync(f.path, join(f.root, "previous.md")); + if (race === "symlink") symlinkSync(join(f.root, "previous.md"), f.path); else writeFileSync(f.path, initial); } + }; + try { const result = race === "revoke" ? await f.commit(draft).catch(e => e) : await f.commit(draft); + if (race !== "revoke") expect(result.receipt.publication).toBe("not_published"); + else expect(result.message).toBe("unauthorized"); + expect(readFileSync(f.path, "utf8")).toBe(race === "bytes" ? initial + "Other tab.\n" : initial); + } finally { if (held !== undefined) closeSync(held); } +}); +test("lock waits recheck authority and base; competing drafts retain exact diffs", async () => { + const f = await fixture(), a = await f.prepare(), b = await f.prepare({ action: "create", rule: { ...rule, id: "troy", selector: { ...rule.selector, host: "example.net" } } }); + const release = await f.lock.acquire(BRAIN_LOCK_KEY); const pending = f.commit(a); writeFileSync(f.path, initial + "Outside edit.\n"); release(); + expect((await pending).receipt.reason).toBe("stale_base"); expect((await f.commit(b)).receipt.publication).toBe("not_published"); + expect((await f.settings.read("odysseus", b.receipt.requestId)).review.proposed).toBe(b.review.proposed); +}); +test("only trust revision is live; ordinary policy and invalid last-valid trust remain honest", async () => { + const f = await fixture(), reader = createGovernancePolicyReader(f.root), ordinary = reader.load(), admitted = structuredClone(await f.settings.snapshot()), draft = await f.prepare(); await f.commit(draft); + const next = await f.settings.snapshot(); expect(next.revision).not.toBe(admitted.revision); expect(admitted.rules).toEqual([]); + writeFileSync(f.path, readFileSync(f.path, "utf8").replace("block_usd: 17", "block_usd: 19")); + expect((await f.settings.snapshot()).revision).toBe(next.revision); + expect(ordinary.policy.budgets.turn.block_usd).toBe(17); expect(reader.load().policy.budgets.turn.block_usd).toBe(19); + writeFileSync(f.path, "invalid"); const invalid = await f.settings.snapshot(); expect(invalid.rules).toEqual(next.rules); expect(invalid.error).toBe("policy_unavailable"); +}); +for (const stage of ["writing", "renamed", "file_published", "committed"]) test(`real process death at ${stage} never guesses publication or republishes`, async () => { + const f = await fixture(), draft = await f.prepare(); await Bun.write(join(f.root, "request.json"), JSON.stringify(draft.review)); + const child = Bun.spawn([process.execPath, join(import.meta.dir, "fixtures/trust-settings-crash.ts"), f.root, stage, draft.receipt.requestId], { stdout: "pipe", stderr: "pipe" }); + const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect({ code, stderr }).toEqual({ code: 77, stderr: "" }); + const recovered = createTrustSettings(f.options), result = await recovered.read("odysseus", draft.receipt.requestId); + expect(result.receipt.publication).toBe(["writing", "renamed"].includes(stage) ? "unknown" : "proved"); + // Equal bytes planted after a pre-publication death cannot establish its proof. + writeFileSync(f.path, draft.review.proposed); + const replay = await recovered.commit("odysseus", { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(replay.receipt.publication).toBe(result.receipt.publication); expect(f.observations).toHaveLength(0); +}); +test("prepare and terminal write failures publish nothing or retain unknown, never replay", async () => { + const f = await fixture(); f.db.exec("CREATE TRIGGER reject_prepare BEFORE INSERT ON trust_settings_operations BEGIN SELECT RAISE(ABORT,'write failed'); END"); + await expect(f.prepare()).rejects.toThrow("write failed"); expect(readFileSync(f.path, "utf8")).toBe(initial); + f.db.exec("DROP TRIGGER reject_prepare"); const draft = await f.prepare(); + f.db.exec("CREATE TRIGGER reject_proof BEFORE UPDATE ON trust_settings_operations WHEN NEW.proof IS NOT NULL BEGIN SELECT RAISE(ABORT,'proof failed'); END"); + expect((await f.commit(draft)).receipt.publication).toBe("unknown"); expect((await f.commit(draft)).receipt.publication).toBe("unknown"); expect(f.observations).toHaveLength(1); +}); +test("outstanding capacity and unsupported repository identities refuse before publication", async () => { + const f = await fixture(); + for (let n = 0; n < 32; n++) await f.prepare(); + let capacity: unknown; try { await f.prepare(); } catch (error) { capacity = error; } expect((capacity as Error)?.message).toBe("capacity"); expect(f.observations).toEqual([]); + let unavailable: unknown; try { await f.prepare({ action: "create", rule: { ...rule, selector: { kind: "github_owner", host: "github.com", owner: "odysseus", ownerId: "1" } } }); } catch (error) { unavailable = error; } + expect((unavailable as Error)?.message).toBe("repository_identity_unavailable"); +}); +test("real HTTP login/owner/CSRF boundary rejects ambient, agent, forged-card and revoked commits", async () => { + const f = await fixture(), password = "ithaca-harbor-test", secret = "fictional-cookie-secret-for-ithaca-tests"; + const config = resolveServerConfig({ AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: await Bun.password.hash(password), COOKIE_SECRET: secret }); + const auth: AuthRuntime = { ...config.auth, host: "127.0.0.1" }; + let mode: "password" | "none" = "password"; + const settings = createTrustSettings({ ...f.options, authority: id => { + const p = resolvePrincipal(f.db, id); + return mode === "password" && p?.kind === "owner" && isUsablePrincipal(p, Date.now()) ? JSON.stringify([p.id, p.createdAt, p.expiresAt]) : null; + } }); + const app = new Hono(); app.route("/api", authRoutes("password", auth, { db: f.db, revoker: { revokePrincipals() {} } })); + app.use("/api/*", async (c, next) => authGuard(mode, auth, f.db)(c, next)); + app.route("/api", createTrustSettingsRoutes({ settings, trustProxy: false })); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch }); cleanup.push(() => server.stop(true)); + const base = `http://127.0.0.1:${server.port}`; + const response = await fetch(`${base}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password }) }); + expect(response.status).toBe(200); const cookie = response.headers.get("set-cookie")!.split(";")[0]!; + const request = (path: string, body?: unknown, extra: Record = {}) => fetch(`${base}/api/trust-settings${path}`, { + method: body === undefined ? "GET" : "POST", headers: { cookie, "content-type": "application/json", origin: base, ...extra }, ...(body === undefined ? {} : { body: JSON.stringify(body) }) }); + const p = await (await request("")).json() as { revision: string; policyHash: string | null }; + const body = { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule } }; + expect((await request("/prepare", body, { origin: "" })).status).toBe(403); + expect((await request("/prepare", body, { origin: "https://example.net", "sec-fetch-site": "same-origin" })).status).toBe(403); + expect((await request("/prepare", { ...body, principalId: "odysseus", channel: "card" })).status).toBe(400); + const preparedResponse = await request("/prepare", body); expect(preparedResponse.status).toBe(200); + const draft = await preparedResponse.json() as Awaited>; + const commit = { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }; + mode = "none"; expect((await request("/commit", commit)).status).toBe(403); mode = "password"; + f.db.exec("UPDATE principals SET kind='agent'"); expect((await request("/commit", commit)).status).toBe(403); + f.db.exec("UPDATE principals SET kind='owner',revoked_at=1"); expect((await request("/commit", commit)).status).toBe(401); + expect(readFileSync(f.path, "utf8")).toBe(initial); expect(p.policyHash).toBe(hash(initial)); +}); +test("real journal observes a Settings operation as user policy without fabricating a turn", async () => { + const f = await fixture(), objects = mkdtempSync(join(f.root, "../objects-")); cleanup.push(() => rmSync(objects, { recursive: true, force: true })); + const native = createNativeJournalFixture(f.root, objects); cleanup.push(() => native.close()); + const journal = createTurnJournal(f.db, { nativeManager: native.manager, brainPath: f.root, dbPath: join(f.root, "ui.db"), objectsRoot: objects }); cleanup.push(() => journal.close()); + const settings = createTrustSettings({ ...f.options, observe: (id, write) => journal.observeSettingsPolicy(id, write) }); + const p = await settings.list("odysseus"); + const draft = await settings.prepare("odysseus", { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule } }); + const saved = await settings.commit("odysseus", { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(saved.receipt.publication).toBe("proved"); + expect(f.db.query("SELECT count(*) n FROM turn_journal_turns").get()).toEqual({ n: 0 }); + expect(f.db.query("SELECT count(*) n FROM policy_proposals").get()).toEqual({ n: 0 }); +}); +test("empty defaults prepare without side effects and publish missing policy ancestors", async () => { + const f = await fixture(); rmSync(join(f.root, "context"), { recursive: true }); + const p = await f.settings.list("odysseus"); expect(p.rules).toEqual([]); expect(p.policyHash).toBeNull(); + const draft = await f.prepare(); expect(draft.review.base).toBeNull(); + expect(() => readFileSync(f.path)).toThrow(); + const recovered = createTrustSettings(f.options); expect((await recovered.read("odysseus", draft.receipt.requestId)).receipt.stage).toBe("prepared"); + expect((await f.commit(draft)).receipt.publication).toBe("proved"); +}); + +test("real process death after prepared commit retains a readable draft and no file effect", async () => { + const f = await fixture(), p = await f.settings.list("odysseus"); + await Bun.write(join(f.root, "request.json"), JSON.stringify({ input: { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule } } })); + const child = Bun.spawn([process.execPath, join(import.meta.dir, "fixtures/trust-settings-crash.ts"), f.root, "prepared", "unused"], { stdout: "pipe", stderr: "pipe" }); + const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]); expect({ code, stderr }).toEqual({ code: 77, stderr: "" }); + const row = f.db.query("SELECT request_id FROM trust_settings_operations").get() as { request_id: string }; + expect((await f.settings.read("odysseus", row.request_id)).receipt.stage).toBe("prepared"); + expect(readFileSync(f.path, "utf8")).toBe(initial); +}); From 0f880443987cd4bb924d7257b23601f866df71c6 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Thu, 5 Nov 2026 12:34:03 +0000 Subject: [PATCH 2/9] CONTRACT: fix(ui-server): describe unavailable trust runtime precisely --- packages/ui-server/src/brain/trust-settings.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 42d35d2938..f452173a4d 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -14,6 +14,7 @@ import { publishProtectedPolicy } from "./policy-publication.js"; import * as writes from "./trust-settings-writes.js"; const hash = (s: string | Uint8Array) => createHash("sha256").update(s).digest("hex"); const id = () => randomBytes(24).toString("base64url"); +const capabilities = { ...TRUST_RUNTIME_CAPABILITIES, readOnlyReason: "Runtime trust enforcement and verified repository identity are unavailable" }; const exactDiff = (before: string | null, after: string) => (before ?? "").split("\n").map(line => `- ${line}`).concat(after.split("\n").map(line => `+ ${line}`)).join("\n"); const digest = z.string().regex(/^[a-f0-9]{64}$/u); const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u); @@ -128,14 +129,14 @@ export function createTrustSettings(options: { if (r.stage === "file_published") receipt = { ...receipt, stage: "partial", publication: r.proof ? "proved" : "unknown", reason: "publication_recorded_completion_incomplete" }; const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); row(principal, request); return { receipt: current(receipt, payload, p), review: { reviewId: payload.reviewId, base: payload.base, proposed: payload.proposed, - diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at }, policy: p, capabilities: TRUST_RUNTIME_CAPABILITIES }; + diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at }, policy: p, capabilities }; }; return { /** Live trust-only projection for future admissions. Ordinary policy snapshots * remain owned by their admitted turn; this never mutates them. */ async snapshot() { return options.lock.withLock(BRAIN_LOCK_KEY, refresh); }, async list(principal: string) { authority(principal); const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); authority(principal); - return { ...p, origins: p.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: p.rules.filter(r => r.selector.kind.startsWith("github_")), capabilities: TRUST_RUNTIME_CAPABILITIES }; }, + return { ...p, origins: p.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: p.rules.filter(r => r.selector.kind.startsWith("github_")), capabilities }; }, read, async prepare(principal: string, raw: unknown) { const auth = authority(principal), input = TrustPrepareSchema.parse(raw); From 4f3fb6951f57cbbbb9b02fb98184cca645ead824 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Thu, 5 Nov 2026 13:34:43 +0000 Subject: [PATCH 3/9] CONTRACT: fix(ui-server): refuse exhausted trust revisions before publication --- .changeset/durable-human-trust-settings.md | 1 + docs/integration-contract/package-api.md | 2 ++ .../ui-server/src/brain/trust-settings.ts | 8 ++++++-- .../ui-server/tests/trust-settings.test.ts | 20 +++++++++++++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/.changeset/durable-human-trust-settings.md b/.changeset/durable-human-trust-settings.md index 6b1bb33189..7a01018c0c 100644 --- a/.changeset/durable-human-trust-settings.md +++ b/.changeset/durable-human-trust-settings.md @@ -3,3 +3,4 @@ --- Add password-owner Settings trust publication with exact-byte reviews, descriptor-bound writes, bounded durable operation receipts and crash-safe readback. Trust enforcement and repository identity acquisition remain unavailable until their independently qualified implementations; saving policy never clears historical taint or grants runtime permission. +Refuse exhausted trust revisions before creating reviews or publishing protected policy bytes. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 5ca936a62a..88bd5db455 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -4831,6 +4831,8 @@ of historical publication proof. No removal receipt claims an enforcing fence. No agent turn, provider message or ordinary governance snapshot is changed. The live trust projection retains last-valid rules on invalid policy, reports an error, and increments its decimal uint64 revision only for trust-list changes. +Exhausted revisions refuse both new reviews and publication of retained reviews +before any protected policy write; request revisions above uint64 also refuse. It is supplied for future admission integration; runtime capabilities remain off. There are at most 32 outstanding reviews per principal, 256 per brain, 10000 diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index f452173a4d..68d83362db 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -17,7 +17,9 @@ const id = () => randomBytes(24).toString("base64url"); const capabilities = { ...TRUST_RUNTIME_CAPABILITIES, readOnlyReason: "Runtime trust enforcement and verified repository identity are unavailable" }; const exactDiff = (before: string | null, after: string) => (before ?? "").split("\n").map(line => `- ${line}`).concat(after.split("\n").map(line => `+ ${line}`)).join("\n"); const digest = z.string().regex(/^[a-f0-9]{64}$/u); -const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u); +const MAX_TRUST_REVISION = 18446744073709551615n; +const revision = z.string().regex(/^(0|[1-9][0-9]{0,19})$/u) + .refine(value => /^(0|[1-9][0-9]{0,19})$/u.test(value) && BigInt(value) <= MAX_TRUST_REVISION, "Revision exhausted"); const ruleId = z.string().regex(/^[A-Za-z0-9_-]{1,128}$/u); const TrustPrepareSchema = z.strictObject({ version: z.literal(1), expectedTrustRevision: revision, expectedPolicyHash: digest.nullable(), change: z.discriminatedUnion("action", [ @@ -108,7 +110,7 @@ export function createTrustSettings(options: { else { await call("projection", brain, old.revision, JSON.stringify(old.rules), old.policyHash, "policy_unavailable"); return { ...old, error: "policy_unavailable" }; } } finally { target?.close(); } const changed = JSON.stringify(old.rules) !== JSON.stringify(rules); - if (changed && BigInt(old.revision) === 18446744073709551615n) throw new TrustSettingsError("capacity", 503); + if (changed && BigInt(old.revision) >= MAX_TRUST_REVISION) throw new TrustSettingsError("capacity", 503); const next = { revision: changed ? String(BigInt(old.revision) + 1n) : old.revision, rules, policyHash, error: null }; await call("projection", brain, next.revision, JSON.stringify(rules), policyHash, null); return next; }; @@ -147,6 +149,7 @@ export function createTrustSettings(options: { const request = await options.lock.withLock(BRAIN_LOCK_KEY, async () => { authority(principal, auth); const p = await refresh(); authority(principal, auth); if (p.error) throw new TrustSettingsError("unavailable", 503); + if (BigInt(p.revision) >= MAX_TRUST_REVISION) throw new TrustSettingsError("capacity", 503); if (p.revision !== input.expectedTrustRevision) throw new TrustSettingsError("stale_revision"); if (p.policyHash !== input.expectedPolicyHash) throw new TrustSettingsError("stale_base"); const change = input.change, ruleId = change.action === "remove" ? change.ruleId : change.rule.id; @@ -185,6 +188,7 @@ export function createTrustSettings(options: { const p = await refresh(); row(principal, input.requestId); if (p.error || p.revision !== payload.input.expectedTrustRevision) throw new TrustSettingsError("stale_revision"); if (p.policyHash !== payload.input.expectedPolicyHash) throw new TrustSettingsError("stale_base"); + if (BigInt(p.revision) >= MAX_TRUST_REVISION) throw new TrustSettingsError("capacity", 503); await save("writing"); await options.checkpoint?.("writing"); if (!matchesTopology(root, payload.topology, false)) throw new TrustSettingsError("stale_base"); target = openGovernancePolicyAnchored(root, { create: p.policyHash === null, created }); diff --git a/packages/ui-server/tests/trust-settings.test.ts b/packages/ui-server/tests/trust-settings.test.ts index 860e701541..aadca6ff7e 100644 --- a/packages/ui-server/tests/trust-settings.test.ts +++ b/packages/ui-server/tests/trust-settings.test.ts @@ -89,6 +89,26 @@ test("only trust revision is live; ordinary policy and invalid last-valid trust expect(ordinary.policy.budgets.turn.block_usd).toBe(17); expect(reader.load().policy.budgets.turn.block_usd).toBe(19); writeFileSync(f.path, "invalid"); const invalid = await f.settings.snapshot(); expect(invalid.rules).toEqual(next.rules); expect(invalid.error).toBe("policy_unavailable"); }); +test("exhausted trust revisions refuse new reviews before reserving or publishing policy", async () => { + const f = await fixture(); await f.settings.snapshot(); + f.db.exec("UPDATE trust_settings_projection SET revision='18446744073709551615'"); + let error: unknown; try { await f.prepare(); } catch (caught) { error = caught; } + expect((error as Error)?.message, "TRUST_REVISION_EXHAUSTION_BEFORE_REVIEW").toBe("capacity"); + expect(f.db.query("SELECT count(*) n FROM trust_settings_operations").get()).toEqual({ n: 0 }); + expect(f.observations).toEqual([]); expect(readFileSync(f.path, "utf8")).toBe(initial); +}); +test("a previously prepared exhausted-revision review cannot publish before failing capacity", async () => { + const f = await fixture(), draft = await f.prepare(); + const row = f.db.query("SELECT payload FROM trust_settings_operations WHERE request_id=?").get(draft.receipt.requestId) as { payload: string }; + const payload = JSON.parse(row.payload); payload.input.expectedTrustRevision = "18446744073709551615"; + f.db.query("UPDATE trust_settings_operations SET payload=? WHERE request_id=?").run(JSON.stringify(payload), draft.receipt.requestId); + f.db.exec("UPDATE trust_settings_projection SET revision='18446744073709551615'"); + const result = await f.commit(draft).catch(error => ({ error })); + expect(readFileSync(f.path, "utf8"), "TRUST_REVISION_EXHAUSTION_BEFORE_PUBLICATION").toBe(initial); + expect(f.observations).toEqual([]); + expect("receipt" in result && result.receipt.publication).toBe("not_published"); + expect("receipt" in result && result.receipt.reason).toBe("capacity"); +}); for (const stage of ["writing", "renamed", "file_published", "committed"]) test(`real process death at ${stage} never guesses publication or republishes`, async () => { const f = await fixture(), draft = await f.prepare(); await Bun.write(join(f.root, "request.json"), JSON.stringify(draft.review)); const child = Bun.spawn([process.execPath, join(import.meta.dir, "fixtures/trust-settings-crash.ts"), f.root, stage, draft.receipt.requestId], { stdout: "pipe", stderr: "pipe" }); From 1f5c0df15285c54dfdd57859e8a97b1efba0ac73 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Thu, 5 Nov 2026 17:40:12 +0000 Subject: [PATCH 4/9] CONTRACT: fix(ui-server): classify trust Settings HTTP routes --- docs/http-api.md | 25 +++++++++++++++++-- .../ui-server/tests/http-inventory.test.ts | 2 +- 2 files changed, 24 insertions(+), 3 deletions(-) diff --git a/docs/http-api.md b/docs/http-api.md index d91f400b30..d27e977ecc 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 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 and chat-deletion routes mounted by `createApp`: 172 unique declared +The inventory includes the additive Queue intake, poke, scheduled-task, session-draft, composer-file, session-recovery 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 and human trust Settings routes mounted by `createApp`: 176 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 @@ -156,6 +156,10 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/journal/configuration-coverage` | S | Read the brain's current untraced configuration-input set | Latest complete inventoried turn only; explicit `unknown`, never an empty list. | | GET | `/api/agent-policy` | I | Read shared admission policy and reported enforcing limits | Read-only Devices & agents facts; no editor or duplicate policy cache. | | GET | `/api/policy-proposals/:turnId/:requestId` | I | Read one principal-owned policy request receipt | Same-request reconciliation only; never writes or reactivates approval. | +| GET | `/api/trust-settings` | I | Read trust policy data and publication availability | Paired Security settings transport (#3608); live password-mode human owners only; runtime trust remains disabled. | +| GET | `/api/trust-settings/:request` | I | Read one owner-bound trust publication receipt and review | Same-request reconciliation only; never republishes or resolves a taint trigger. | +| POST | `/api/trust-settings/prepare` | I | Prepare one exact-base trust change | Paired Security settings transport; same-origin JSON and live owner authority; repository create/edit awaits verified host identity. | +| POST | `/api/trust-settings/commit` | I | Publish the exact owner-reviewed trust change | Shared descriptor-bound publisher; bounded durable receipt; saved policy does not imply runtime enforcement. | | GET | `/api/sessions/:id/recovery` | S | Read a session's latest accepted work and pending interactions | Trackers and independent session clients (#964, D52); preserve the revision ordering, Activity terminal proof, honest unknown and the no-execution boundary. | | POST | `/api/queue` | S | Queue authenticated CLI intake without filing content | CLI and independent intake clients; preserve explicit key, provenance and queue receipt. | | GET | `/api/schedules` | S | List stored scheduled tasks, cancelled ones included | CLI and independent schedule clients; preserve keys, receipts, operator approval and the no-execution boundary. | @@ -205,7 +209,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 172 declared endpoints are mounted regardless of backend, renderer or +All 176 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. @@ -1781,3 +1785,20 @@ unknown is terminal for automatic retry. Three attempts per episode/subscription are the maximum, with one/five-minute delays only after known non-delivery. Restored episodes never regain notification authority. See [Storage history](storage-history.md) for sampling, recovery and physical costs. + +## Human trust Settings publication + +The four `/api/trust-settings` operations are internal paired Security settings +transport. Their exact review/receipt shapes and limits are described in the +[publication contract](integration-contract/package-api.md#human-trust-settings-publication). +They require a live password-mode human owner; mutation additionally requires a +present exact same-origin Origin and bounded JSON. Principal, voice and channel +claims in a body supply no authority. Receipts are private, no-store, scoped to +the served brain and requesting owner, and readback never repeats a write. + +Publication reuses the protected policy writer without an agent turn. Prepared +state, reviewed bytes/base, publication proof and partial/unknown completion +survive restart. Saved origin/tunnel rules do not enable unbuilt trust admission; +repository create/edit refuses until independent host identity is available. +Removal/readback remain available for existing rules. Revision exhaustion refuses +before protected publication. No historical trigger is resolved by these routes. diff --git a/packages/ui-server/tests/http-inventory.test.ts b/packages/ui-server/tests/http-inventory.test.ts index fcf5e513d3..c61c626606 100644 --- a/packages/ui-server/tests/http-inventory.test.ts +++ b/packages/ui-server/tests/http-inventory.test.ts @@ -20,7 +20,7 @@ test("real app method/path inventory equals the complete classified HTTP specifi expect(proseCounts).toEqual([declared.length, declared.length]); } const middleware = [...new Set(t.routes.filter((r) => r.method === "ALL").map((r) => r.path))].sort(); - expect(middleware).toEqual(["/*", "/api/*", "/api/apify*", "/api/auth/passkey/*", "/api/auth/principals/*", "/api/brain/briefing", "/api/brain/list", "/api/brain/search", "/api/brain/stats", "/api/brain/stats/history", "/api/graph/*", "/api/internal/inbox/poke", "/api/sessions/:sessionId/turns/:turnId/revert*", "/api/storage*", "/api/storage/maintenance*", "/api/storage/removals*"]); + expect(middleware).toEqual(["/*", "/api/*", "/api/apify*", "/api/auth/passkey/*", "/api/auth/principals/*", "/api/brain/briefing", "/api/brain/list", "/api/brain/search", "/api/brain/stats", "/api/brain/stats/history", "/api/graph/*", "/api/internal/inbox/poke", "/api/sessions/:sessionId/turns/:turnId/revert*", "/api/storage*", "/api/storage/maintenance*", "/api/storage/removals*", "/api/trust-settings*"]); expect(t.routes.filter((r) => r.method === "ALL" && r.path === "/*")).toHaveLength(staticRoot ? 3 : 2); expect(t.routes.some((r) => r.method === "HEAD" || r.method === "OPTIONS")).toBe(false); } finally { await t.close(); } From 00cc3e0930d70c8cdf94124a0ee8911b73832476 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 18 Nov 2026 10:18:14 +0000 Subject: [PATCH 5/9] CONTRACT: feat(ui-server): resolve Settings repository identity without Git acquisition --- .../ithaca-settings-repository-identity.md | 5 + .../decisions/reference-source-acquisition.md | 12 +- docs/integration-contract/package-api.md | 11 + .../src/brain/github-reference-access.ts | 241 ++++++++++-------- .../tests/github-reference-access.test.ts | 153 +++++++++++ 5 files changed, 315 insertions(+), 107 deletions(-) create mode 100644 .changeset/ithaca-settings-repository-identity.md diff --git a/.changeset/ithaca-settings-repository-identity.md b/.changeset/ithaca-settings-repository-identity.md new file mode 100644 index 0000000000..d9c613c437 --- /dev/null +++ b/.changeset/ithaca-settings-repository-identity.md @@ -0,0 +1,5 @@ +--- +"@schlessera/brain-ui-server": minor +--- + +Add owner-only GitHub repository metadata lookup for Settings with live grant, credential-recipient and operation-authority checks. diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index c6b3651b74..6d83622c06 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -189,7 +189,7 @@ reclamation is observed. ## Fixed GitHub wire and identity authority (#3613) The concrete access owner (`createGitHubReferenceAccess`, -`packages/ui-server/src/brain/github-reference-access.ts:19-151`) uses the +`packages/ui-server/src/brain/github-reference-access.ts:19-186`) uses the fixed transport (`createGitHubReferenceWire`, `packages/ui-server/src/brain/github-reference-wire.ts:19-254`). @@ -205,6 +205,16 @@ Owner identity uses its own anonymous `/users/` operation, without a Git channel or credentialed mode. Parsed identity data carries no trust or approved-owner-boundary claim. +Settings repository lookup shares that metadata authority without selecting a +Git revision or fabricating an agent turn. Its separate owner-only operation +returns fresh repository/owner IDs through the same fixed anonymous-first path, +including the requesting owner's own grant for private metadata. Neither that +result nor anonymous owner lookup approves a trust boundary. The Settings +publisher must retain its independent human authority and bind a fresh identity +observation to reviewed publication; changing names or IDs cannot inherit an +old review. Cancellation and operation authority are retained before waits and +rechecked before returning the identity, including after wire shutdown. + The fixed wire shares one operation allowance across metadata, Git discovery, authentication and fetch, and charges the real turn counter. It counts TLS framing and both directions. Before forwarding each chunk it rechecks live diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 1e0772efd0..4b4e994961 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -92,6 +92,17 @@ before the proxy exists, so expired GitHub source is withheld without network until an explicit turn request validates it. Other legacy repository transports remain unqualified for repository trust. +The same internal access service provides owner-only repository metadata +lookup without a Git revision, acquisition, agent turn or Git channel. It +reuses the anonymous-first and live private-grant/API-recipient checks above; +owner namespace lookup remains anonymous-only. Both operations snapshot the +principal, target, cancellation and operation-authority callback before waits, +recheck them after waits including shutdown, and return fresh fixed-endpoint +identity data. They return no credential, relay capability, approved-owner +boundary or source-trust flag. The Settings publisher still supplies its +independent password-mode human authority and must revalidate identity before +publishing. A lookup at review time is not permanent identity approval. + Migration 089 records a retained source acquisition's host-issued identity, brain/principal/turn, stable repository and owner identities, resolved ref, commit/tree, sealed native root ID/UUID/creation generation, selected grant and diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index 8a75f33bbb..abf7020e14 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -33,125 +33,154 @@ export function createGitHubReferenceAccess(options: { throw new ReferenceTransportError("denied", "reference principal is no longer available"); }; + /** Shared metadata authority, without selecting a Git revision or starting a turn. */ + async function repositoryMetadata(input: RequestBounds & { principalId: string; repository: unknown; + withdrawPublic?: () => Promise }, ownerOnly: boolean) { + // Retain the operation's identity across waits; caller-owned objects cannot + // switch the principal, target, cancellation or authority callback mid-read. + const { principalId, repository: repositoryInput, current: currentOperation, signal, withdrawPublic, ...bounds } = input; + const assertOperation = () => { + signal?.throwIfAborted(); + if (currentOperation && !currentOperation()) throw new ReferenceTransportError("denied", "the reference operation is no longer available"); + principal(principalId, ownerOnly); + }; + const location = githubReferenceRepository(repositoryInput), repository = referenceRepository(location.cloneUrl); + assertOperation(); + let grant: ReferenceGrant | null = null, credential: string | null = null; + const authorize = (recipient: "git" | "metadata", credentialed: boolean) => { + assertOperation(); + if (grant) { + const current = coveringReferenceGrant(options.db, { brain: options.brain, principalId, repository, now: now() }); + // Recreated grants and a newly selected narrower grant cannot inherit this operation. + if (!current || current.id !== grant.id || current.credential !== grant.credential) + throw new ReferenceTransportError("denied", "the selected reference grant changed"); + if (recipient === "metadata" && credentialed && current.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) + throw new ReferenceTransportError("denied", "the selected grant does not permit the API credential recipient"); + if (credentialed && (!current.credential || options.credentials[current.credential] !== credential)) + throw new ReferenceTransportError("denied", "the selected host credential changed"); + } else if (credentialed) throw new ReferenceTransportError("denied", "anonymous acquisition cannot dispatch a credential"); + }; + const wire = await createGitHubReferenceWire({ ...bounds, signal, repository: location.cloneUrl, ...options.wireTransport, authorize }); + let openingMetadata = true; + try { + let result = await wire.metadata(null); + if (result.status === 401 || result.status === 404) { + await withdrawPublic?.(); + // That observation is already contained. A missing private grant + // is not a second metadata observation after the withdrawal waits. + openingMetadata = false; + assertOperation(); + grant = coveringReferenceGrant(options.db, { brain: options.brain, principalId, repository, now: now() }); + if (!grant?.credential || grant.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) + throw new ReferenceTransportError("denied", "private identity needs a live reference grant and explicit API credential permission"); + credential = options.credentials[grant.credential] ?? null; + if (!credential) throw new ReferenceTransportError("unavailable", "the granted host credential is not configured"); + authorize("metadata", true); + openingMetadata = true; + result = await wire.metadata(credential); + } + authorize("metadata", credential !== null); + if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable"); + const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.cloneUrl, result.value); + if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); + openingMetadata = false; + // Source/worktree effects outlive wire shutdown, but not this authority. + const assertAuthority = () => { + authorize("git", credential !== null); authorize("metadata", credential !== null); + }; + const assertCurrent = () => { wire.signal.throwIfAborted(); assertAuthority(); }; + assertCurrent(); + return Object.freeze({ identity: Object.freeze(identity), repository, credential, wire, + domain: grant ? "private" as const : "public" as const, grantId: grant?.id ?? null, assertCurrent, assertAuthority, + /** A final fixed metadata observation must still describe this exact acquisition. */ + async revalidate() { + try { + assertCurrent(); + const result = await wire.metadata(credential); + assertCurrent(); + if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.cloneUrl, result.value))) + throw new ReferenceTransportError("denied", "GitHub repository identity changed during acquisition"); + } catch (error) { + const interrupted = signal?.aborted || (currentOperation && !currentOperation()); + await wire.close(); + if (interrupted) throw error; + throw new GitHubReferenceMetadataError(error); + } + }, + close: () => wire.close(), + }); + } catch (error) { + // Retain an observed metadata failure before shutdown can outlive its turn. + const failure = openingMetadata && !signal?.aborted && (!currentOperation || currentOperation()) + ? new GitHubReferenceMetadataError(error) : error; + await wire.close(); throw failure; + } + } + return { - /** Settings still supplies its independent password-mode human publication authority. */ + /** Settings supplies independent password-mode human publication authority. */ async owner(input: RequestBounds & { principalId: string; owner: unknown }): Promise { - const owner = githubReferenceOwner(input.owner); - principal(input.principalId, true); - const wire = await createGitHubReferenceWire({ ...input, owner: owner.owner, ...options.wireTransport, - authorize: () => principal(input.principalId, true) }); + const { principalId, owner: ownerInput, current, signal, ...bounds } = input; + const owner = githubReferenceOwner(ownerInput); + const assertCurrent = () => { + signal?.throwIfAborted(); + if (current && !current()) throw new ReferenceTransportError("denied", "the Settings operation is no longer available"); + principal(principalId, true); + }; + assertCurrent(); + const wire = await createGitHubReferenceWire({ ...bounds, signal, owner: owner.owner, ...options.wireTransport, authorize: assertCurrent }); + let identity: GitHubReferenceOwner & { ownerId: string }; try { const result = await wire.metadata(null); - principal(input.principalId, true); + assertCurrent(); if (result.status !== 200) throw new ReferenceTransportError("unavailable", "GitHub owner identity is unavailable"); - return parseGitHubOwnerMetadata(owner.owner, result.value); + identity = parseGitHubOwnerMetadata(owner.owner, result.value); } finally { await wire.close(); } + assertCurrent(); + return Object.freeze(identity); + }, + + /** Fixed metadata only. No revision, Git channel, token or approval proof escapes. */ + async repository(input: RequestBounds & { principalId: string; repository: unknown }): Promise { + const access = await repositoryMetadata(input, true); + try { access.assertCurrent(); } + finally { await access.close(); } + // Wire shutdown is an asynchronous wait too. Its intentional abort does + // not invalidate the caller's independent live Settings authority. + access.assertAuthority(); + return access.identity; }, /** Open one host-only budget; anonymous metadata always precedes any permitted private retry. */ async open(input: RequestBounds & { principalId: string; repository: unknown; revision: unknown; /** The source host must hide prior public exposure before a credentialed retry can await. */ withdrawPublic?: () => Promise }) { - const location = githubReferenceRepository(input.repository), repository = referenceRepository(location.cloneUrl); const revision = referenceRevision(input.revision); - principal(input.principalId); - let grant: ReferenceGrant | null = null, credential: string | null = null; - const authorize = (recipient: "git" | "metadata", credentialed: boolean) => { - if (input.current && !input.current()) throw new ReferenceTransportError("denied", "the acquiring turn is no longer available"); - principal(input.principalId); - if (grant) { - const current = coveringReferenceGrant(options.db, { brain: options.brain, principalId: input.principalId, repository, now: now() }); - // Recreated grants and a newly selected narrower grant cannot inherit this operation. - if (!current || current.id !== grant.id || current.credential !== grant.credential) - throw new ReferenceTransportError("denied", "the selected reference grant changed"); - if (recipient === "metadata" && credentialed && current.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) - throw new ReferenceTransportError("denied", "the selected grant does not permit the API credential recipient"); - if (credentialed && (!current.credential || options.credentials[current.credential] !== credential)) - throw new ReferenceTransportError("denied", "the selected host credential changed"); - } else if (credentialed) throw new ReferenceTransportError("denied", "anonymous acquisition cannot dispatch a credential"); - }; - const wire = await createGitHubReferenceWire({ ...input, repository: location.cloneUrl, ...options.wireTransport, authorize }); - let openingMetadata = true; - try { - let result = await wire.metadata(null); - if (result.status === 401 || result.status === 404) { - await input.withdrawPublic?.(); - // That observation is already contained. A missing private grant - // is not a second metadata observation after the withdrawal waits. - openingMetadata = false; - principal(input.principalId); - grant = coveringReferenceGrant(options.db, { brain: options.brain, principalId: input.principalId, repository, now: now() }); - if (!grant?.credential || grant.metadataCredentialRecipient !== REFERENCE_METADATA_CREDENTIAL_RECIPIENT) - throw new ReferenceTransportError("denied", "private identity needs a live reference grant and explicit API credential permission"); - credential = options.credentials[grant.credential] ?? null; - if (!credential) throw new ReferenceTransportError("unavailable", "the granted host credential is not configured"); - authorize("metadata", true); - openingMetadata = true; - result = await wire.metadata(credential); - } - authorize("metadata", credential !== null); - if (result.status !== 200) throw new ReferenceTransportError([401, 403, 404].includes(result.status) ? "denied" : "unavailable", "GitHub repository identity is unavailable"); - const identity: GitHubReferenceIdentity = parseGitHubReferenceMetadata(location.cloneUrl, result.value); - if (!grant && identity.private) throw new ReferenceTransportError("denied", "anonymous metadata cannot establish public source access"); - openingMetadata = false; - // Source/worktree effects outlive wire shutdown, but not this authority. - const assertAuthority = () => { - authorize("git", credential !== null); authorize("metadata", credential !== null); - }; - const assertCurrent = () => { wire.signal.throwIfAborted(); assertAuthority(); }; - let resolved: Extract | undefined; - assertCurrent(); - return Object.freeze({ - identity: Object.freeze(identity), - domain: grant ? "private" as const : "public" as const, - grantId: grant?.id ?? null, - revision, - signal: wire.signal, - bytes: wire.bytes, - assertCurrent, assertAuthority, - async resolve() { - assertCurrent(); - const result = await options.transport.resolve({ repository, revision, token: credential, wire, signal: wire.signal }); - assertCurrent(); - if (resolved && (!result.ok || result.ref !== resolved.ref || result.commit !== resolved.commit)) { - await wire.close(); throw new ReferenceTransportError("invalid", "the selected Git reference changed during acquisition"); - } - if (result.ok) resolved = { ...result }; - return result; - }, - async fetch(root: string) { - assertCurrent(); - if (!resolved) throw new ReferenceTransportError("invalid", "reference fetch needs its resolved branch or tag"); - const result = await options.transport.fetch({ repository, ref: resolved.ref, root, token: credential, wire, signal: wire.signal }); - assertCurrent(); - if (result.commit !== resolved.commit) { - await wire.close(); throw new ReferenceTransportError("invalid", "the fetched commit differs from the selected reference"); - } - return result; - }, - /** A final fixed metadata observation must still describe this exact acquisition. */ - async revalidate() { - try { - assertCurrent(); - const result = await wire.metadata(credential); - assertCurrent(); - if (result.status !== 200 || !sameGitHubReferenceIdentity(identity, parseGitHubReferenceMetadata(location.cloneUrl, result.value))) - throw new ReferenceTransportError("denied", "GitHub repository identity changed during acquisition"); - } catch (error) { - const interrupted = input.signal?.aborted || (input.current && !input.current()); - await wire.close(); - if (interrupted) throw error; - throw new GitHubReferenceMetadataError(error); - } - }, - close: () => wire.close(), - }); - } catch (error) { - // Retain an observed metadata failure before shutdown can outlive its turn. - const failure = openingMetadata && !input.signal?.aborted && (!input.current || input.current()) - ? new GitHubReferenceMetadataError(error) : error; - await wire.close(); throw failure; - } + const access = await repositoryMetadata(input, false); + const { identity, domain, grantId, wire, credential, repository, assertCurrent, assertAuthority, revalidate, close } = access; + let resolved: Extract | undefined; + return Object.freeze({ identity, domain, grantId, revision, signal: wire.signal, bytes: wire.bytes, assertCurrent, assertAuthority, revalidate, close, + async resolve() { + assertCurrent(); + const result = await options.transport.resolve({ repository, revision, token: credential, wire, signal: wire.signal }); + assertCurrent(); + if (resolved && (!result.ok || result.ref !== resolved.ref || result.commit !== resolved.commit)) { + await close(); throw new ReferenceTransportError("invalid", "the selected Git reference changed during acquisition"); + } + if (result.ok) resolved = { ...result }; + return result; + }, + async fetch(root: string) { + assertCurrent(); + if (!resolved) throw new ReferenceTransportError("invalid", "reference fetch needs its resolved branch or tag"); + const result = await options.transport.fetch({ repository, ref: resolved.ref, root, token: credential, wire, signal: wire.signal }); + assertCurrent(); + if (result.commit !== resolved.commit) { + await close(); throw new ReferenceTransportError("invalid", "the fetched commit differs from the selected reference"); + } + return result; + }, + }); }, }; } diff --git a/packages/ui-server/tests/github-reference-access.test.ts b/packages/ui-server/tests/github-reference-access.test.ts index cc8fbbcc3e..b19303f41c 100644 --- a/packages/ui-server/tests/github-reference-access.test.ts +++ b/packages/ui-server/tests/github-reference-access.test.ts @@ -213,6 +213,159 @@ test("owner Settings identity is anonymous and owner-scoped, without approval or } finally { await f.close(); } }); +test("Settings repository identity has no Git phase or revision and stays anonymous", async () => { + const f = await fixture(); f.grant({ principalId: f.owner.id }); + try { + const pending = Promise.resolve().then(() => f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca" })); + await expect(pending, "SETTINGS_REPOSITORY_RESOLVES_WITHOUT_GIT_OR_AGENT_TURN").resolves.toEqual({ + owner: "odysseus", repository: "ithaca", canonical: "https://github.com/odysseus/ithaca", cloneUrl: "https://github.com/odysseus/ithaca.git", + metadataUrl: "https://api.github.com/repos/odysseus/ithaca", repositoryId: "101", ownerId: "201", private: false, + }); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }]); + expect(f.git, "SETTINGS_METADATA_NEVER_DISPATCHES_GIT").toEqual([]); + await expect(f.service().repository({ ...f.bounds, principalId: f.agent.id, repository: "odysseus/ithaca" }), + "SETTINGS_PUBLIC_METADATA_REQUIRES_OWNER").rejects.toMatchObject({ reason: "denied" }); + expect(f.received).toHaveLength(1); + } finally { await f.close(); } +}); + +test("owner metadata rechecks the Settings operation after its actual DNS wait", async () => { + let release!: () => void, ready!: () => void, current = true; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await fixture({ lookup: async () => { ready(); await held; return [{ address: "93.184.216.34", family: 4 }]; }, + metadata: () => Response.json({ id: 201, login: "Odysseus", type: "User", url: "https://api.github.com/users/Odysseus", html_url: "https://github.com/Odysseus" }) }); + const pending = f.service().owner({ ...f.bounds, principalId: f.owner.id, owner: "odysseus", current: () => current }); + try { + await reached; current = false; release(); + const result = await pending.then(value => ({ ok: true, value }), () => ({ ok: false })); + expect(result, "SETTINGS_OWNER_OPERATION_RECHECKED_AFTER_DNS").toEqual({ ok: false }); + expect(f.connections, "SETTINGS_ENDED_OWNER_OPERATION_NEVER_CONNECTS").toEqual([]); + expect(f.received).toEqual([]); + } finally { release(); await pending.catch(() => {}); await f.close(); } +}); + +test("private Settings metadata uses the owner's own live grant and separately permitted API recipient", async () => { + const f = await fixture({ private: true }); + f.grant({ principalId: f.owner.id }); + try { + await expect(f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca" }), + "SETTINGS_PRIVATE_METADATA_USES_OWN_GRANT").resolves.toMatchObject({ repositoryId: "101", ownerId: "201", private: true }); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }, + { path: "/repos/odysseus/ithaca", authorization: `Bearer ${token}` }]); + await expect(f.service().repository({ ...f.bounds, principalId: f.agent.id, repository: "odysseus/ithaca" }), + "SETTINGS_METADATA_REQUIRES_OWNER").rejects.toMatchObject({ reason: "denied" }); + expect(f.received).toHaveLength(2); + expect(f.git).toEqual([]); + } finally { await f.close(); } +}); + +for (const kind of ["absent", "legacy", "other-brain", "other-principal", "sibling-repository", "revoked", "credentialless"] as const) + test(`Settings private metadata refuses ${kind} authority without credential probing`, async () => { + let tokenReads = 0; + const f = await fixture({ private: true, credentials: { get GITHUB_TOKEN() { tokenReads++; return token; } } }); + try { + if (kind !== "absent") { + const grant = f.grant({ principalId: f.owner.id, ...(kind === "legacy" ? { metadataCredentialRecipient: null } + : kind === "other-brain" ? { brain: "troy-brain" } + : kind === "other-principal" ? { principalId: f.agent.id } + : kind === "sibling-repository" ? { repositoryPrefix: "https://github.com/odysseus-crew" } + : kind === "credentialless" ? { credential: null, metadataCredentialRecipient: null } : {}) }); + if (kind === "revoked") revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: grant.id, now: Date.now() }); + } + await expect(f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca" }), + "SETTINGS_METADATA_NEEDS_OWN_LIVE_GRANT_AND_API_PERMISSION").rejects.toMatchObject({ reason: "denied" }); + expect(tokenReads, "SETTINGS_METADATA_REFUSAL_NEVER_PROBES_CREDENTIAL").toBe(0); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }]); + expect(f.git).toEqual([]); + } finally { await f.close(); } + }); + +for (const kind of ["operation", "principal", "grant", "recipient", "credential", "cancel"] as const) + test(`Settings private metadata fences ${kind} loss during credentialed DNS`, async () => { + let release!: () => void, ready!: () => void, lookups = 0, current = true; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const credentials: Record = { GITHUB_TOKEN: token }, controller = new AbortController(); + const f = await fixture({ private: true, credentials, lookup: async () => { + if (++lookups === 2) { ready(); await held; } return [{ address: "93.184.216.34", family: 4 }]; + } }); + const grant = f.grant({ principalId: f.owner.id }); + const pending = f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca", current: () => current, signal: controller.signal }); + try { + await reached; + if (kind === "operation") current = false; + else if (kind === "principal") revokePrincipal(f.db, f.owner.id, Date.now()); + else if (kind === "grant") revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: grant.id, now: Date.now() }); + else if (kind === "recipient") f.db.query("UPDATE reference_grants SET metadata_credential_recipient=NULL WHERE id=?").run(grant.id); + else if (kind === "credential") credentials.GITHUB_TOKEN = "changed-fixture-token"; + else controller.abort(); + release(); + const result = await pending.then(value => ({ ok: true, value }), () => ({ ok: false })); + expect(result, "SETTINGS_AUTHORITY_RECHECKED_AFTER_CREDENTIALED_DNS").toEqual({ ok: false }); + expect(f.connections, "SETTINGS_LOST_AUTHORITY_NEVER_REACHES_CREDENTIALED_TCP").toHaveLength(1); + expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }]); + expect(f.git).toEqual([]); + } finally { release(); await pending.catch(() => {}); await f.close(); } + }); + +for (const kind of ["owner", "repository"] as const) + test(`Settings ${kind} identity retains its original caller and operation across waits`, async () => { + let release!: () => void, ready!: () => void, current = true; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await fixture({ lookup: async () => { ready(); await held; return [{ address: "93.184.216.34", family: 4 }]; } }); + const input = { ...f.bounds, principalId: f.owner.id, owner: "odysseus", repository: "odysseus/ithaca", current: () => current }; + const pending = kind === "owner" ? f.service().owner(input) : f.service().repository(input); + try { + await reached; current = false; + input.principalId = f.agent.id; input.current = () => true; input.owner = "penelope"; input.repository = "penelope/loom"; + release(); + expect(await pending.then(() => true, () => false), "SETTINGS_CALLER_MUTATION_CANNOT_REPLACE_OPERATION").toBe(false); + expect(f.connections).toEqual([]); expect(f.received).toEqual([]); + } finally { release(); await pending.catch(() => {}); await f.close(); } + }); + +test("each Settings lookup observes fresh provider identity and refuses redirects or unknown metadata", async () => { + const changes = [identity(), { ...identity(), id: 102 }, { ...identity(), owner: { id: 202, login: "Odysseus" } }, + { ...identity(), name: "Fleet", full_name: "Odysseus/Fleet", clone_url: "https://github.com/Odysseus/Fleet.git", url: "https://api.github.com/repos/Odysseus/Fleet" }]; + let selected = 0; + const f = await fixture({ metadata: () => Response.json(changes[selected]) }); + try { + const lookup = (repository = "odysseus/ithaca") => f.service().repository({ ...f.bounds, principalId: f.owner.id, repository }); + expect(await lookup()).toMatchObject({ repositoryId: "101", ownerId: "201" }); + selected = 1; expect(await lookup(), "SETTINGS_NAME_REUSE_RETURNS_NEW_IDENTITY").toMatchObject({ repositoryId: "102", ownerId: "201" }); + selected = 2; expect(await lookup(), "SETTINGS_OWNER_REUSE_RETURNS_NEW_BOUNDARY").toMatchObject({ repositoryId: "101", ownerId: "202" }); + selected = 3; + await expect(lookup(), "SETTINGS_RENAME_CANNOT_BORROW_OLD_NAME_RESPONSE").rejects.toThrow(); + expect(await lookup("odysseus/fleet"), "SETTINGS_RENAME_REQUIRES_FRESH_EXACT_NAME_OBSERVATION").toMatchObject({ repositoryId: "101", ownerId: "201", repository: "fleet" }); + expect(f.git).toEqual([]); + } finally { await f.close(); } + for (const status of [302, 403, 429, 500]) { + let tokenReads = 0; + const control = await fixture({ metadata: () => new Response(null, { status }), credentials: { get GITHUB_TOKEN() { tokenReads++; return token; } } }); + control.grant({ principalId: control.owner.id }); + try { + await expect(control.service().repository({ ...control.bounds, principalId: control.owner.id, repository: "odysseus/ithaca" }), + "SETTINGS_UNKNOWN_METADATA_CANNOT_DISPATCH_CREDENTIAL").rejects.toThrow(); + expect(tokenReads).toBe(0); expect(control.received).toHaveLength(1); expect(control.git).toEqual([]); + } finally { await control.close(); } + } +}); + +test("Settings cancellation closes a pending DNS operation before that lookup finishes", async () => { + let release!: () => void, ready!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const controller = new AbortController(); + const f = await fixture({ lookup: async () => { ready(); await held; return [{ address: "93.184.216.34", family: 4 }]; } }); + const pending = f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca", signal: controller.signal }); + let timer: ReturnType | undefined; + try { + await reached; controller.abort(); + const result = await Promise.race([pending.then(() => "identity", () => "cancelled"), + new Promise(resolve => { timer = setTimeout(() => resolve("still_waiting"), 5000); })]); + expect(result, "SETTINGS_CANCEL_DOES_NOT_WAIT_FOR_DNS").toBe("cancelled"); + expect(f.connections).toEqual([]); expect(f.received).toEqual([]); + } finally { if (timer) clearTimeout(timer); release(); await pending.catch(() => {}); await f.close(); } +}); + test("one acquisition binds a short revision before network and refuses a moved fetched commit before checkout", async () => { const f = await fixture({ fetchCommit: "b".repeat(40) }); try { From eeff70b582d7430b221dec8ed446cd0c5f407dd7 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Wed, 18 Nov 2026 10:26:16 +0000 Subject: [PATCH 6/9] feat(ui-server): retain metadata authority through Settings publication waits --- .../decisions/reference-source-acquisition.md | 7 ++++-- docs/integration-contract/package-api.md | 5 +++- .../src/brain/github-reference-access.ts | 7 ++++-- .../tests/github-reference-access.test.ts | 24 +++++++++++++++++++ 4 files changed, 38 insertions(+), 5 deletions(-) diff --git a/docs/decisions/reference-source-acquisition.md b/docs/decisions/reference-source-acquisition.md index 6d83622c06..00a656460c 100644 --- a/docs/decisions/reference-source-acquisition.md +++ b/docs/decisions/reference-source-acquisition.md @@ -189,7 +189,7 @@ reclamation is observed. ## Fixed GitHub wire and identity authority (#3613) The concrete access owner (`createGitHubReferenceAccess`, -`packages/ui-server/src/brain/github-reference-access.ts:19-186`) uses the +`packages/ui-server/src/brain/github-reference-access.ts:19-189`) uses the fixed transport (`createGitHubReferenceWire`, `packages/ui-server/src/brain/github-reference-wire.ts:19-254`). @@ -213,7 +213,10 @@ result nor anonymous owner lookup approves a trust boundary. The Settings publisher must retain its independent human authority and bind a fresh identity observation to reviewed publication; changing names or IDs cannot inherit an old review. Cancellation and operation authority are retained before waits and -rechecked before returning the identity, including after wire shutdown. +rechecked before returning the identity, including after wire shutdown. A +repository observation retains a synchronous authority check over its selected +grant and credential for the final publication boundary; invoking it does not +refresh metadata or approve the target. The fixed wire shares one operation allowance across metadata, Git discovery, authentication and fetch, and charges the real turn counter. It counts TLS diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 4b4e994961..cfdc823a44 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -98,7 +98,10 @@ reuses the anonymous-first and live private-grant/API-recipient checks above; owner namespace lookup remains anonymous-only. Both operations snapshot the principal, target, cancellation and operation-authority callback before waits, recheck them after waits including shutdown, and return fresh fixed-endpoint -identity data. They return no credential, relay capability, approved-owner +identity data. Repository lookup also retains a synchronous `assertAuthority()` +callback over that exact lookup's selected grant/credential and operation; it +allows the publisher to recheck after later waits without selecting replacement +authority. This callback is not metadata refresh or approval evidence. They return no credential, relay capability, approved-owner boundary or source-trust flag. The Settings publisher still supplies its independent password-mode human authority and must revalidate identity before publishing. A lookup at review time is not permanent identity approval. diff --git a/packages/ui-server/src/brain/github-reference-access.ts b/packages/ui-server/src/brain/github-reference-access.ts index abf7020e14..35049c83e0 100644 --- a/packages/ui-server/src/brain/github-reference-access.ts +++ b/packages/ui-server/src/brain/github-reference-access.ts @@ -141,14 +141,17 @@ export function createGitHubReferenceAccess(options: { }, /** Fixed metadata only. No revision, Git channel, token or approval proof escapes. */ - async repository(input: RequestBounds & { principalId: string; repository: unknown }): Promise { + async repository(input: RequestBounds & { principalId: string; repository: unknown }): Promise { const access = await repositoryMetadata(input, true); try { access.assertCurrent(); } finally { await access.close(); } // Wire shutdown is an asynchronous wait too. Its intentional abort does // not invalidate the caller's independent live Settings authority. access.assertAuthority(); - return access.identity; + // A later synchronous publication fence must retain this operation's + // selected grant and credential, rather than select a replacement grant. + // This checks authority only; a new review/commit still needs fresh metadata. + return Object.freeze({ ...access.identity, assertAuthority: access.assertAuthority }); }, /** Open one host-only budget; anonymous metadata always precedes any permitted private retry. */ diff --git a/packages/ui-server/tests/github-reference-access.test.ts b/packages/ui-server/tests/github-reference-access.test.ts index b19303f41c..2831359d14 100644 --- a/packages/ui-server/tests/github-reference-access.test.ts +++ b/packages/ui-server/tests/github-reference-access.test.ts @@ -220,6 +220,7 @@ test("Settings repository identity has no Git phase or revision and stays anonym await expect(pending, "SETTINGS_REPOSITORY_RESOLVES_WITHOUT_GIT_OR_AGENT_TURN").resolves.toEqual({ owner: "odysseus", repository: "ithaca", canonical: "https://github.com/odysseus/ithaca", cloneUrl: "https://github.com/odysseus/ithaca.git", metadataUrl: "https://api.github.com/repos/odysseus/ithaca", repositoryId: "101", ownerId: "201", private: false, + assertAuthority: expect.any(Function), }); expect(f.received).toEqual([{ path: "/repos/odysseus/ithaca", authorization: null }]); expect(f.git, "SETTINGS_METADATA_NEVER_DISPATCHES_GIT").toEqual([]); @@ -259,6 +260,29 @@ test("private Settings metadata uses the owner's own live grant and separately p } finally { await f.close(); } }); +for (const kind of ["grant", "replace", "narrower", "recipient", "credential", "principal", "operation", "cancel"] as const) + test(`Settings metadata retains a final synchronous ${kind} authority fence after wire cleanup`, async () => { + let current = true; + const credentials: Record = { GITHUB_TOKEN: token }, controller = new AbortController(); + const f = await fixture({ private: true, credentials }), grant = f.grant({ principalId: f.owner.id }); + try { + const result = await f.service().repository({ ...f.bounds, principalId: f.owner.id, repository: "odysseus/ithaca", + current: () => current, signal: controller.signal }); + expect(() => result.assertAuthority(), "SETTINGS_FRESH_METADATA_AUTHORITY_REMAINS_USABLE_AFTER_CLEANUP").not.toThrow(); + if (kind === "grant" || kind === "replace") { + revokeReferenceGrant(f.db, { brain, principalId: f.owner.id, id: grant.id, now: Date.now() }); + if (kind === "replace") f.grant({ principalId: f.owner.id }); + } else if (kind === "narrower") f.grant({ principalId: f.owner.id, repositoryPrefix: "https://github.com/odysseus/ithaca" }); + else if (kind === "recipient") f.db.query("UPDATE reference_grants SET metadata_credential_recipient=NULL WHERE id=?").run(grant.id); + else if (kind === "credential") credentials.GITHUB_TOKEN = "changed-fixture-token"; + else if (kind === "principal") revokePrincipal(f.db, f.owner.id, Date.now()); + else if (kind === "operation") current = false; + else controller.abort(); + expect(() => result.assertAuthority(), "SETTINGS_FINAL_PUBLICATION_FENCE_RETAINS_LOOKUP_AUTHORITY").toThrow(); + expect(f.received).toHaveLength(2); expect(f.git).toEqual([]); + } finally { await f.close(); } + }); + for (const kind of ["absent", "legacy", "other-brain", "other-principal", "sibling-repository", "revoked", "credentialless"] as const) test(`Settings private metadata refuses ${kind} authority without credential probing`, async () => { let tokenReads = 0; From b841e598a25dc1044924c1f38f9cf104c4529306 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:35:44 +0000 Subject: [PATCH 7/9] CONTRACT: feat(ui-server): complete host-verified trust Settings publication --- .changeset/durable-human-trust-settings.md | 2 +- api-report/ui-server.txt | 2 +- docs/decisions/bounded-multi-read.md | 2 +- docs/decisions/claude-code-runtime.md | 2 +- docs/decisions/governed-writable-workers.md | 18 +- docs/decisions/http-api-boundary.md | 8 +- docs/decisions/journal-database.md | 2 +- docs/decisions/scheduled-tasks.md | 2 +- docs/decisions/session-principals.md | 6 +- docs/decisions/session-safety-reviews.md | 11 + docs/http-api.md | 9 +- docs/integration-contract/package-api.md | 42 +++- docs/integration-contract/wire.md | 2 +- .../plans/async-collaboration-requirements.md | 2 +- docs/plans/async-collaboration.md | 2 +- docs/plans/chat-history-deletion.md | 2 +- docs/plans/reviewable-session-safety.md | 2 +- .../094_trust_github_boundaries.sql | 10 + packages/ui-server/src/app.ts | 5 +- .../src/brain/trust-github-identity.ts | 59 +++++ .../src/brain/trust-settings-writes.ts | 25 +- .../ui-server/src/brain/trust-settings.ts | 86 +++++-- packages/ui-server/src/brain/turn-journal.ts | 4 +- .../ui-server/src/routes/trust-settings.ts | 9 +- .../tests/fixtures/trust-settings-crash.ts | 14 +- .../ui-server/tests/trust-settings.test.ts | 227 +++++++++++++++++- 26 files changed, 494 insertions(+), 61 deletions(-) create mode 100644 packages/ui-server/migrations/094_trust_github_boundaries.sql create mode 100644 packages/ui-server/src/brain/trust-github-identity.ts diff --git a/.changeset/durable-human-trust-settings.md b/.changeset/durable-human-trust-settings.md index 7a01018c0c..c301400878 100644 --- a/.changeset/durable-human-trust-settings.md +++ b/.changeset/durable-human-trust-settings.md @@ -2,5 +2,5 @@ "@schlessera/brain-ui-server": minor --- -Add password-owner Settings trust publication with exact-byte reviews, descriptor-bound writes, bounded durable operation receipts and crash-safe readback. Trust enforcement and repository identity acquisition remain unavailable until their independently qualified implementations; saving policy never clears historical taint or grants runtime permission. +Add password-owner Settings trust publication with exact-byte reviews, descriptor-bound writes, bounded durable operation receipts and crash-safe readback. Verify GitHub repository and owner identities through the bounded host transport and retain approved-owner evidence only with proved publication. Runtime trust enforcement remains unavailable; saving policy never clears historical taint or grants runtime permission. Refuse exhausted trust revisions before creating reviews or publishing protected policy bytes. diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index dcfb2df7c7..e3630fc0ae 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2658,7 +2658,7 @@ signatures (every public export and the types it is made of) isHeld(): boolean; maintain: () => Promise; observe(): Promise; - observeSettingsPolicy(_operationId: string, approvedWrite: () => void): Promise; + observeSettingsPolicy(_operationId: string, approvedWrite: () => Promise | void): Promise; observeUserPolicy(turnId: string, approvedWrite: () => Promise | void): Promise; onObservation(observer: (turnId: string, facts: { changedPaths: number; diff --git a/docs/decisions/bounded-multi-read.md b/docs/decisions/bounded-multi-read.md index b5cbc9ec2f..231d9ce4ca 100644 --- a/docs/decisions/bounded-multi-read.md +++ b/docs/decisions/bounded-multi-read.md @@ -151,7 +151,7 @@ parallel default, with concurrency 1. proves only `read_file`, `write_file` and `edit_file`. So (`toolObservation`, `packages/ui-server/src/brain/tool-observation.ts:37-42`) calls it `unproven`, and - (`toolEnded`, `packages/ui-server/src/brain/turn-journal.ts:584-591`) + (`toolEnded`, `packages/ui-server/src/brain/turn-journal.ts:614-621`) observes every result and marks the turn lasting. Four reads made four observations, sequential or parallel. One batch call made one. That is a real host-side saving, small in time (8.3 ms against 1.4 ms on the fixture). diff --git a/docs/decisions/claude-code-runtime.md b/docs/decisions/claude-code-runtime.md index 78a25de3b7..6af13c6e44 100644 --- a/docs/decisions/claude-code-runtime.md +++ b/docs/decisions/claude-code-runtime.md @@ -64,7 +64,7 @@ next to it. of this binary. The only version probe in the server is for the `brain` CLI (`Probe the selected content CLI`, `packages/ui-server/src/brain/client.ts:180-248`, called at - `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:510`). + `probeBrainCliVersion(config.brainPath`, `packages/ui-server/src/app.ts:513`). `brain doctor` runs `claude mcp list` from `PATH` (`which("claude")`, `packages/core/src/cli/commands/doctor.ts:507-511`) — the user's own Claude Code on their own machine, to check the MCP registration, not the server's diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index f346e70e15..b6b7afdc65 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -1258,7 +1258,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:159-254`). +(`const held`, `packages/ui-server/src/brain/policy-proposal.ts:160-252`). Every retained turn has one initially collapsed receipt. Known no-change is zero; legacy/unknown detail and unknown cost/limits remain explicitly unknown. @@ -1274,7 +1274,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:217-251`). First publication +`packages/ui-server/src/brain/policy-proposal.ts:218-232`). 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 @@ -1533,7 +1533,7 @@ starts one per result and carries on (`void host.journal?.toolEnded`, `packages/ui-server/src/ws/bridge-capabilities/emission.ts:273`). The wait is the observation's hold. `held` takes it synchronously, before it queues the capture -(`function held`, `packages/ui-server/src/brain/turn-journal.ts:279-300`), +(`function held`, `packages/ui-server/src/brain/turn-journal.ts:293-314`), and the scope monitor's hold freezes every active turn's productive workers until the capture completes (`before() {`, `packages/ui-server/src/brain/turn-scope.ts:158-166`). Pi's agent loop runs in @@ -1545,7 +1545,7 @@ tracked the hold, not the bridge call. proven read-only, no other call of an active turn is still running, and no active turn has run a call whose effects may outlast it (`toolEnded(turnId: string, toolUseId: string)`, -`packages/ui-server/src/brain/turn-journal.ts:584-591`). Admission, turn end, +`packages/ui-server/src/brain/turn-journal.ts:614-621`). Admission, turn end, the 15-second timer, scope-limit observations, approved policy writes and removal coverage observe exactly as before. @@ -1804,7 +1804,7 @@ these versions as metadata-only and never open them for retention kind, mode, size and its ignored flag, carries `metadataOnly: true` and records its opaque change stamp, with no content hash and no symlink target. Two versions of equal size are told apart by that stamp, as ignored ones are -(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:83`), +(`const identity`, `packages/ui-server/src/brain/turn-journal.ts:84`), so every observed refresh remains a recorded change. A metadata-only version is an intentional observation state: it adds no `missing` entry and does not make the turn partial. Removal coverage never treats the family as eligible, and history @@ -1816,7 +1816,7 @@ stays now counts its largest size once too, rather than each version. **History.** History presents every index-family version as metadata-only however it was recorded, so a version an earlier release retained is no longer read -(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:76-81`). +(`const presented`, `packages/ui-server/src/brain/turn-journal.ts:77-82`). The reader groups these entries as the search index, recorded by size and timestamps only, with no review action. Preview reports `metadata_only` and download has nothing to serve. History revert and Undo read that same @@ -1873,7 +1873,7 @@ keeps its bytes. **The purge.** It runs once, on the journal's write worker, when the journal opens, after interrupted turns have been ended -(`while (await ledger.call`, `packages/ui-server/src/brain/turn-journal.ts:129`), +(`while (await ledger.call`, `packages/ui-server/src/brain/turn-journal.ts:144`), in at most two accounted commits whose progress is recorded in `turn_journal_allocation.index_purge` (`purgeIndexVersions(): IndexPurgeResult`, @@ -4744,7 +4744,7 @@ attribution. If an existing same-session/turn taint event precedes an agent observation, the journal retains its source ID with that change. Replay never infers taint from a later event, and absence of evidence does not assert complete untrusted-input detection. User history operations are not tainted agent writes -(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:413-478`). +(`async function observe`, `packages/ui-server/src/brain/turn-journal.ts:430-495`). Claude auto-memory persists outside the authoritative brain. Its validated native copy-out wraps each changed direct `.md` note in host journal retention: @@ -4767,7 +4767,7 @@ memory completion of the earlier 0.42.0 steering slice, not a widening of memory providers or a claim of capturing intervening external writes. The copy-out boundary is `const write`, `packages/ui-backend-claude/src/worker-state.ts:210-224`; retention/finalization is `persistClaudeMemory`, -`packages/ui-server/src/brain/turn-journal.ts:698-728`; destination-bound recovery +`packages/ui-server/src/brain/turn-journal.ts:741-771`; destination-bound recovery is `const target`, `packages/ui-server/src/brain/turn-revert.ts:113-123`. ### Concurrent edits diff --git a/docs/decisions/http-api-boundary.md b/docs/decisions/http-api-boundary.md index 86362d84c0..8673144d74 100644 --- a/docs/decisions/http-api-boundary.md +++ b/docs/decisions/http-api-boundary.md @@ -46,11 +46,11 @@ explicit supported rows, not silently excluded by this distinction. The source audit on 2026-09-30 used `e0875269b21b707482545be9e94901acb897893b`. The public health mount precedes auth -(`createHealthRoutes`, `packages/ui-server/src/app.ts:1102`), the API guard follows -public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1123`), and the -WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1364`). +(`createHealthRoutes`, `packages/ui-server/src/app.ts:1107`), the API guard follows +public ceremonies (`authGuard`, `packages/ui-server/src/app.ts:1128`), and the +WebSocket admission is separate (`"/ws"`, `packages/ui-server/src/app.ts:1378`). Static serving is conditional (`if (options.staticRoot)`, -`packages/ui-server/src/app.ts:1384-1405`). That order establishes access; +`packages/ui-server/src/app.ts:1398-1419`). That order establishes access; it does not select compatibility status. A hermetic real-app launch, with temporary brain root, in-memory database, diff --git a/docs/decisions/journal-database.md b/docs/decisions/journal-database.md index 3d0f6bc01f..8c165d7cb7 100644 --- a/docs/decisions/journal-database.md +++ b/docs/decisions/journal-database.md @@ -97,7 +97,7 @@ that no pre-charge covers. The evidence is on the issue. readers understand the arrays until then, and an empty legacy array stays "no set recorded". The brain's current set is the one the most recent complete, inventoried turn recorded - (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:779-785`). + (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:822-828`). The sets table is an ordinary rowid table, as every journal table is: the operational backup copies and compares journal rows in rowid order. diff --git a/docs/decisions/scheduled-tasks.md b/docs/decisions/scheduled-tasks.md index 0de2fee2e7..ef752abfb8 100644 --- a/docs/decisions/scheduled-tasks.md +++ b/docs/decisions/scheduled-tasks.md @@ -23,7 +23,7 @@ Source inspected at `b5c30c180df5584584f261b446c4d440380d2441`: (`else if (item.status === "scheduled"`, `packages/ui-server/src/inbox/actions.ts:196-197`). The runtime ticks every minute (`INBOX_TICK_MS`, `packages/ui-server/src/inbox/runtime.ts:11-13`). - Production app wiring supplies recovery and budgets, without a dispatcher - (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:592-608`). + (`// Recovery/heartbeat only.`, `packages/ui-server/src/app.ts:597-613`). A scripted nonempty ready-item test still reports no claim, attempt or Activity root. That proves disabled wiring, not safe execution of a schedule. - Headless plumbing checks backend support, a usable principal, lifetime and diff --git a/docs/decisions/session-principals.md b/docs/decisions/session-principals.md index 01ade27e3f..b4c90f5548 100644 --- a/docs/decisions/session-principals.md +++ b/docs/decisions/session-principals.md @@ -96,9 +96,9 @@ Both reviewers verified every row below against the source. | Cookie verify | `auth.ts:265-296` | strict `^(\d+)\.(\d+)$`, safe integers, future/expired rejection, `cookieEpoch === sessionsEpoch(db)` | | Global epoch | `auth.ts:302-318` | `settings` row; missing = 0; non-integer **throws** | | Global revoke | `auth.ts:321-330` | `setSetting` (overflow-guarded) + `clients.closeAll(1008, …)` | -| Auth routes | `authRoutes`, `app.ts:1108` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1124`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | -| Passkey management | `passkeyManagementRoutes`, `app.ts:1132` | mounted **after** the guard ("Mount AFTER the auth guard") | -| WS guard | `"/ws"`, `app.ts:1364-1381` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | +| Auth routes | `authRoutes`, `app.ts:1113` | mounted **before** the guard at `authGuard(authMode`, `app.ts:1128`; logout guards itself (`resolveCookiePrincipal(c, auth, deps.db)`, `auth.ts:798`) | +| Passkey management | `passkeyManagementRoutes`, `app.ts:1137` | mounted **after** the guard ("Mount AFTER the auth guard") | +| WS guard | `"/ws"`, `app.ts:1378-1395` | origin → `isWsAuthorized` (returns a boolean, `auth.ts:221-237`) → capacity → upgrade | | WS upgrade | `ws/connection.ts:262-264` | `createWsUpgrade` ignores the request context | | WS admission | `ws/connection.ts:84` | `clients.add(ws)` — the socket's identity is unknown | | Turn record | `ws/run-session.ts:136-144` | recorder built from `{turnId, sessionId, billing}`; `RunningTurn` (`ws/turns.ts:55-77`) has no actor | diff --git a/docs/decisions/session-safety-reviews.md b/docs/decisions/session-safety-reviews.md index 58627d516b..c4e7adff74 100644 --- a/docs/decisions/session-safety-reviews.md +++ b/docs/decisions/session-safety-reviews.md @@ -219,6 +219,17 @@ and no fabricated agent turn. A human Settings operation has its own host audit identity and exact reviewed policy bytes/base hash. No personal accounts, configuration or real deployment details belong in the public tree. +The v1 repository selector keeps its stable repository ID and canonical owner +name. The independent provider owner ID is retained as host publication +evidence, preserving that policy format. A prepared metadata observation or +matching current file bytes cannot create an approved-owner boundary: the +operation's descriptor-bound write and directory sync precede the FULL durable +transaction that records its proof and owner identity together. Current boundary +facts survive bounded operation-receipt pruning, and removal or selector change +retires them. They establish the owner's historical reviewed choice, not current +repository identity, private access or runtime permission. Every later qualified +read still needs independently verified immutable provenance and fresh identity. + Source trust and recipient permission are distinct. Incoming trust never silently permits sending data while another trigger restricts the chat. Recipient permission defaults off and needs its own explicit review. Exact diff --git a/docs/http-api.md b/docs/http-api.md index 8479b8e8c9..8bb9812427 100644 --- a/docs/http-api.md +++ b/docs/http-api.md @@ -160,7 +160,7 @@ client code has a gap. Source owners are listed after the table. | GET | `/api/policy-proposals/:turnId/:requestId` | I | Read one principal-owned policy request receipt | Same-request reconciliation only; never writes or reactivates approval. | | GET | `/api/trust-settings` | I | Read trust policy data and publication availability | Paired Security settings transport (#3608); live password-mode human owners only; runtime trust remains disabled. | | GET | `/api/trust-settings/:request` | I | Read one owner-bound trust publication receipt and review | Same-request reconciliation only; never republishes or resolves a taint trigger. | -| POST | `/api/trust-settings/prepare` | I | Prepare one exact-base trust change | Paired Security settings transport; same-origin JSON and live owner authority; repository create/edit awaits verified host identity. | +| POST | `/api/trust-settings/prepare` | I | Prepare one exact-base trust change | Paired Security settings transport; same-origin JSON and live owner authority; repository create/edit independently verifies host metadata. | | POST | `/api/trust-settings/commit` | I | Publish the exact owner-reviewed trust change | Shared descriptor-bound publisher; bounded durable receipt; saved policy does not imply runtime enforcement. | | GET | `/api/sessions/:id/safety` | S | Read bounded revisioned host safety evidence | Authenticated principal of the history owner's account (#3952); immutable records, snapshot aggregate/high-water, scoped cursor, explicit coverage/unavailable, no mutation (#3604). | | POST | `/api/sessions/:id/safety/reviews/prepare` | S | Prepare review of one finalized safety occurrence | Live password-mode human owner, exact Origin and bounded JSON; host-issued body/brain/principal/generation-bound handle (#3603). | @@ -2393,6 +2393,11 @@ the served brain and requesting owner, and readback never repeats a write. Publication reuses the protected policy writer without an agent turn. Prepared state, reviewed bytes/base, publication proof and partial/unknown completion survive restart. Saved origin/tunnel rules do not enable unbuilt trust admission; -repository create/edit refuses until independent host identity is available. +repository create/edit independently verifies fixed-endpoint metadata at review +and again inside the publication observation window. Browser IDs cannot +self-verify; unknown or changed identity withholds the write. Approved owner +boundaries derive from this operation's durable publication proof and are not +inferred from matching policy bytes. Owner-scope review explicitly covers +future repositories currently in that namespace. Runtime trust remains disabled. Removal/readback remain available for existing rules. Revision exhaustion refuses before protected publication. No historical trigger is resolved by these routes. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 451f9943e0..32961ec082 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5583,15 +5583,30 @@ capability, HTTP endpoint, history DTO or provider conversation changes here. The optional owner-only `/api/trust-settings` HTTP surface is a policy-publication building block. `GET /api/trust-settings` reads the current trust-only revision, -exact policy hash, `origins`, `repositories`, and disabled runtime capabilities. +exact policy hash, `origins`, `repositories`, repository-identity availability, +and disabled runtime enforcement capabilities. `POST /api/trust-settings/prepare` accepts strict version-1 JSON with `expectedTrustRevision`, `expectedPolicyHash` and exactly one `change`: `{action:create|edit,rule}` or `{action:remove,ruleId}`. The host issues the request/operation/review IDs and retains exact base/proposed UTF-8 policy text, reviewed SHA-256 and a 15-minute expiry. A selector change requires remove/add. -Repository creates/edits refuse `repository_identity_unavailable`: browser IDs -are not host identity verification and this surface implements no metadata -transport. Existing repository rules can be read and removed. +Repository creates/edits use the concrete fixed host metadata path. Browser +stable IDs must match independently observed provider IDs. The review retains +`repositoryIdentity` (or null) and `includesFutureRepositories`; owner rules +explicitly include future repositories currently owned by that namespace. +Every commit obtains fresh metadata inside the journal observation window, +compares repository/owner IDs, canonical names and privacy with the reviewed +identity, and checks its exact selected grant/credential authority at the final +synchronous publication boundary. Unknown metadata, changed identity, missing +private grants and lost API recipient permission withhold publication. No agent +turn or generic relay is created. Existing repository rules can still be read +and removed when metadata is unavailable. + +Each metadata operation has a 30-second deadline and a 1 MiB charged-wire +allowance further bounded by the ordinary policy's egress byte limit. Host +allow/deny rules remain effective; public metadata stays anonymous. HTTP +cancellation ends that operation. The lookup establishes no incoming source +trust, general recipient permission or Git acquisition/write capability. `POST /api/trust-settings/commit` accepts only `{version:1,requestId,reviewId, reviewedBytesHash}`; `GET /api/trust-settings/:request` only reads that caller's @@ -5604,7 +5619,15 @@ Receipts bind principal/credential lifetime, served brain, operation, request, exact base/topology and reviewed hash. Prepared state precedes any write; the shared privileged publisher syncs staging bytes and the containing directory. Only a FULL durable proof written after this operation's publication establishes -`publication:proved`. A crash in writing/rename before that proof returns +`publication:proved`. The same transaction retains a bounded current GitHub +owner-boundary fact tied to the operation, principal, authority, exact reviewed +bytes and selector. It survives bounded operation-receipt pruning, while rule +removal/target change retires it. Equal current policy bytes and prepared +metadata cannot create this evidence. It is historical publication evidence; +a future source-rule verifier must still qualify the actual read and fresh +current identity independently. The internal `repositoryApproval` reader is +host-only and grants no runtime capability. The original v1 selector format is +unchanged. A crash in writing/rename before that proof returns `unknown`, even if current file bytes match. Retries with identical commit data only read the original outcome; changed data conflicts. Expired handles can never create operations. Prepared/readback text survives stale-base refusal. @@ -5616,17 +5639,24 @@ runtime enforcement. Current responses use `partial` for saved policy because `currentRule:present|removed|changed|unknown` is refreshed on reads, independently of historical publication proof. No removal receipt claims an enforcing fence. No agent turn, provider message or ordinary governance snapshot is changed. +The journal awaits asynchronous metadata and publication before releasing its +Settings observation window; a missing publication callback cannot produce proof. The live trust projection retains last-valid rules on invalid policy, reports an error, and increments its decimal uint64 revision only for trust-list changes. Exhausted revisions refuse both new reviews and publication of retained reviews before any protected policy write; request revisions above uint64 also refuse. It is supplied for future admission integration; runtime capabilities remain off. +The HTTP boundary admits at most 32 concurrent requests per principal and 256 +for the served brain, including lock waiters; excess requests return retryable +`busy` (503) before joining another wait and recover as earlier requests finish. There are at most 32 outstanding reviews per principal, 256 per brain, 10000 receipts and 16 MiB reserved payload/receipt storage. New requests fail at capacity; live receipts are not evicted. Terminal receipts survive at least 24 hours. Unknown writes are never replayed, including after pruning. Settings -migration 080 has no dependency on occurrence-ledger migration 079/081+; the +migration 080 has no dependency on occurrence-ledger migration 079/081+; +migration 094 adds the owner-boundary evidence without changing earlier applied +migrations. The loader applies each unapplied filename in sorted order on every startup. ## Extraction classifier setting (additive, 0.45.0, #4088) diff --git a/docs/integration-contract/wire.md b/docs/integration-contract/wire.md index 924af4b6af..f855f99514 100644 --- a/docs/integration-contract/wire.md +++ b/docs/integration-contract/wire.md @@ -55,7 +55,7 @@ reports the paths observed so far, a lower bound, and an empty partial reports summary retained before this field, or sent by an older server, omits it or reports `null`: the count is unknown, never zero, and a client names the `changedFiles` figure as recorded entries rather than files. The count is -(`const KEPT_CHANGE`, `packages/ui-server/src/brain/turn-journal.ts:54-57`). +(`const KEPT_CHANGE`, `packages/ui-server/src/brain/turn-journal.ts:55-58`). **Configuration coverage set (additive, #3257).** Untraced configuration inputs are a property of the brain's configuration, so the host stores each distinct diff --git a/docs/plans/async-collaboration-requirements.md b/docs/plans/async-collaboration-requirements.md index d49fa30511..63eb3dfda3 100644 --- a/docs/plans/async-collaboration-requirements.md +++ b/docs/plans/async-collaboration-requirements.md @@ -226,7 +226,7 @@ Stated before the requirements because five of them derive from it. that is the shape to copy, including its `close()` lifecycle. - R19. **The cron backstop has independent authorization before the general guard.** Mount it on the existing listener before - (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1123`). + (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1128`). Authorize a boot-minted ephemeral token, rotated each boot and stored in a 0600 runtime file, with the actual socket address as an additional check. Proxy headers cannot authorize it. The poke succeeds in every auth mode diff --git a/docs/plans/async-collaboration.md b/docs/plans/async-collaboration.md index 5cd82b5ed0..2925d2ac39 100644 --- a/docs/plans/async-collaboration.md +++ b/docs/plans/async-collaboration.md @@ -131,7 +131,7 @@ system gate. It is not a prerequisite to rebuild or a new independent package. owns manual triggers/history; it does not tick the inbox. - **Two connections:** (`export function createUiDb(`, `packages/ui-server/src/db/client.ts:28-45`) sets WAL, foreign keys and a 5-second busy timeout. Claims are immediate transactions. -- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1123`) follows public routes; +- **Auth mounting:** (`app.use("/api/*", authGuard(`, `packages/ui-server/src/app.ts:1128`) follows public routes; (`export function authGuard(`, `packages/ui-server/src/middleware/auth.ts:184-244`) binds principals in each auth mode. An internal poke needs independent token authorization before this guard. - **Permission parking:** (`const requestPermission`, `packages/ui-server/src/ws/bridge-capabilities/permissions.ts:19-188`). Timeout unwind is diff --git a/docs/plans/chat-history-deletion.md b/docs/plans/chat-history-deletion.md index c9b0e0195d..e1f61f8818 100644 --- a/docs/plans/chat-history-deletion.md +++ b/docs/plans/chat-history-deletion.md @@ -337,7 +337,7 @@ Preserve the existing bounded-wait ownership distinction during that drain. writers; rejection retains the original cleanup continuation, writer and reader until genuine settlement, rather than authorizing their replacement (`guardSqliteCleanup`, `packages/ui-server/src/db/write-worker.ts:206-234`; -`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1474-1524`). +`close: () => closing ??= guardSqliteCleanup`, `packages/ui-server/src/app.ts:1488-1538`). The native lease manager retains its own pending operations and durable unknown root outcomes through close (`return { client, writer, recoverDeadOwners`, `packages/ui-server/src/brain/native-brain-leases.ts:320-333`). A caller deadline diff --git a/docs/plans/reviewable-session-safety.md b/docs/plans/reviewable-session-safety.md index 89839a6541..5f57f1cc9e 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:132-161`). 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:100-275`). + (`createPolicyProposals`, `packages/ui-server/src/brain/policy-proposal.ts:101-254`). - 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/migrations/094_trust_github_boundaries.sql b/packages/ui-server/migrations/094_trust_github_boundaries.sql new file mode 100644 index 0000000000..6928695180 --- /dev/null +++ b/packages/ui-server/migrations/094_trust_github_boundaries.sql @@ -0,0 +1,10 @@ +-- Current approved-owner evidence, derived only from a proved Settings +-- publication. It is never a second source of policy or runtime permission. +CREATE TABLE trust_settings_github_boundaries ( + brain_id TEXT NOT NULL, + rule_id TEXT NOT NULL, + selector TEXT NOT NULL, + identity TEXT NOT NULL, + proof TEXT NOT NULL, + PRIMARY KEY (brain_id, rule_id) +); diff --git a/packages/ui-server/src/app.ts b/packages/ui-server/src/app.ts index 636b26e133..0dba58ebf5 100644 --- a/packages/ui-server/src/app.ts +++ b/packages/ui-server/src/app.ts @@ -1,5 +1,6 @@ import { createTrustSettings } from "./brain/trust-settings.js"; import { createTrustSettingsRoutes } from "./routes/trust-settings.js"; +import { createTrustGitHubIdentity } from "./brain/trust-github-identity.js"; import { SafetyHistory } from "./governance/safety-history.js"; import { createSessionSafetyRoutes } from "./routes/session-safety.js"; import { createOwnerSafetyReviewRoutes } from "./routes/owner-safety-review.js"; @@ -544,8 +545,9 @@ export async function createApp(options: CreateAppOptions = {}): Promise referenceWorktreeDependents(db, rootId) }) : undefined; @@ -1333,6 +1335,7 @@ export async function createApp(options: CreateAppOptions = {}): Promise { if (authMode !== "password") return null; const p = resolvePrincipal(db, id); diff --git a/packages/ui-server/src/brain/trust-github-identity.ts b/packages/ui-server/src/brain/trust-github-identity.ts new file mode 100644 index 0000000000..8abbecfeb6 --- /dev/null +++ b/packages/ui-server/src/brain/trust-github-identity.ts @@ -0,0 +1,59 @@ +/** Fixed host metadata for one human Settings operation, independent of an agent turn. */ +import type { TrustSelector } from "@schlessera/brain-common/internal/governance-policy"; +import { startEgressProxy } from "@schlessera/brain-ui-sdk/internal"; +import type { createGitHubReferenceAccess } from "./github-reference-access.js"; +import { createGovernancePolicyReader } from "./governance-policy.js"; +import { ReferenceTransportError } from "./reference-transport.js"; + +type GitHubSelector = Extract; +export interface TrustGitHubIdentity { + selector: GitHubSelector; + ownerId: string; + private: boolean | null; +} + +/** Identity data is retained with the reviewed bytes; the callback is host-only and ephemeral. */ +export function createTrustGitHubIdentity(options: { + root: string; + access: Pick, "owner" | "repository">; +}) { + const reader = createGovernancePolicyReader(options.root); + return { + async resolve(input: { principalId: string; selector: GitHubSelector; policyHash: string | null; + current(): boolean; signal?: AbortSignal }) { + const { principalId, current, signal, policyHash } = input, selector = structuredClone(input.selector); + const check = () => { + signal?.throwIfAborted(); + if (!current()) throw new ReferenceTransportError("denied", "The Settings owner operation ended."); + }; + check(); + const loaded = reader.load(); + if (loaded.errors.length || loaded.hash !== policyHash) throw new ReferenceTransportError("denied", "The reviewed policy base changed."); + // Metadata is a fixed read initiated by the human, outside any model + // conversation. Ordinary host allow/deny and byte controls still apply. + const maxBytes = Math.min(1048576, loaded.policy.egress.max_bytes_per_turn ?? 1048576); + const egress = await startEgressProxy({ mode: loaded.policy.egress.mode, allow: loaded.policy.egress.allow, + deny: loaded.policy.egress.deny, maxBytes, outwardHosts: [], signal, observe() {} }); + try { + check(); + const bounds = { principalId, egress, maxBytes, timeoutMs: 30000, current, signal }; + let identity: TrustGitHubIdentity, assertAuthority: () => void; + if (selector.kind === "github_owner") { + const observed = await options.access.owner({ ...bounds, owner: selector.owner }); + if (observed.ownerId !== selector.ownerId) throw new ReferenceTransportError("denied", "The requested owner identity differs from current metadata."); + identity = { selector, ownerId: observed.ownerId, private: null }; + assertAuthority = check; + } else { + // A selector already contains a canonical name: add the clone suffix + // exactly once so a literal repository suffix remains literal. + const observed = await options.access.repository({ ...bounds, repository: `https://github.com/${selector.owner}/${selector.repository}.git` }); + if (observed.repositoryId !== selector.repositoryId) throw new ReferenceTransportError("denied", "The requested repository identity differs from current metadata."); + identity = { selector, ownerId: observed.ownerId, private: observed.private }; + assertAuthority = () => { check(); observed.assertAuthority(); }; + } + assertAuthority(); + return { identity, networkBytes: maxBytes - egress.remainingBytes(), assertAuthority }; + } finally { egress.stop(); } + }, + }; +} diff --git a/packages/ui-server/src/brain/trust-settings-writes.ts b/packages/ui-server/src/brain/trust-settings-writes.ts index 87212a29c4..effd311c14 100644 --- a/packages/ui-server/src/brain/trust-settings-writes.ts +++ b/packages/ui-server/src/brain/trust-settings-writes.ts @@ -15,11 +15,30 @@ export function setup(db: Database): WriteProcedures { return "prepared"; }).immediate(); }, - stage(id: string, stage: string, receipt: string, proof: string | null, now: number) { - db.query("UPDATE trust_settings_operations SET stage=?, receipt=?, proof=coalesce(?,proof), retain_until=max(retain_until,?) WHERE request_id=?").run(stage, receipt, proof, now + 86400000, id); + stage(id: string, stage: string, receipt: string, proof: string | null, now: number, + boundary?: { brain: string; ruleId: string; selector: string; identity: string }) { + return db.transaction(() => { + db.query("UPDATE trust_settings_operations SET stage=?, receipt=?, proof=coalesce(?,proof), retain_until=max(retain_until,?) WHERE request_id=?").run(stage, receipt, proof, now + 86400000, id); + if (boundary) { + if (stage !== "file_published" || !proof) throw new Error("A GitHub boundary requires this operation's durable publication proof"); + db.query(`INSERT INTO trust_settings_github_boundaries VALUES (?,?,?,?,?) + ON CONFLICT(brain_id,rule_id) DO UPDATE SET selector=excluded.selector,identity=excluded.identity,proof=excluded.proof`) + .run(boundary.brain, boundary.ruleId, boundary.selector, boundary.identity, proof); + } + }).immediate(); }, projection(brain: string, revision: string, rules: string, hash: string | null, error: string | null) { - db.query("INSERT INTO trust_settings_projection VALUES (?,?,?,?,?) ON CONFLICT(brain_id) DO UPDATE SET revision=excluded.revision,rules=excluded.rules,policy_hash=excluded.policy_hash,error=excluded.error").run(brain, revision, rules, hash, error); + return db.transaction(() => { + db.query("INSERT INTO trust_settings_projection VALUES (?,?,?,?,?) ON CONFLICT(brain_id) DO UPDATE SET revision=excluded.revision,rules=excluded.rules,policy_hash=excluded.policy_hash,error=excluded.error").run(brain, revision, rules, hash, error); + // At most one retained boundary per current rule; equal file bytes + // alone never create one. Invalid policy retains last-valid facts. + if (!error) { + const current = new Map((JSON.parse(rules) as { id: string; selector: unknown }[]).map(rule => [rule.id, JSON.stringify(rule.selector)])); + const boundaries = db.query("SELECT rule_id,selector FROM trust_settings_github_boundaries WHERE brain_id=?").all(brain) as { rule_id: string; selector: string }[]; + for (const row of boundaries) if (current.get(row.rule_id) !== row.selector) + db.query("DELETE FROM trust_settings_github_boundaries WHERE brain_id=? AND rule_id=?").run(brain, row.rule_id); + } + }).immediate(); }, }; } diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 68d83362db..b48516217c 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -12,9 +12,10 @@ import { BRAIN_LOCK_KEY, type KeyedLock } from "@schlessera/brain-ui-sdk/server" import { procedureCaller, type SqliteWriter } from "../db/write-worker.js"; import { publishProtectedPolicy } from "./policy-publication.js"; import * as writes from "./trust-settings-writes.js"; +import type { createTrustGitHubIdentity, TrustGitHubIdentity } from "./trust-github-identity.js"; +import { ReferenceTransportError } from "./reference-transport.js"; const hash = (s: string | Uint8Array) => createHash("sha256").update(s).digest("hex"); const id = () => randomBytes(24).toString("base64url"); -const capabilities = { ...TRUST_RUNTIME_CAPABILITIES, readOnlyReason: "Runtime trust enforcement and verified repository identity are unavailable" }; const exactDiff = (before: string | null, after: string) => (before ?? "").split("\n").map(line => `- ${line}`).concat(after.split("\n").map(line => `+ ${line}`)).join("\n"); const digest = z.string().regex(/^[a-f0-9]{64}$/u); const MAX_TRUST_REVISION = 18446744073709551615n; @@ -39,7 +40,7 @@ interface Receipt { publication: "not_published" | "proved" | "unknown"; ruleId: string; publishedTrustRevision: string | null; currentRule: "present" | "removed" | "changed" | "unknown"; enforcement: "unavailable"; reason: string | null; } -interface Payload { input: Prepare; reviewId: string; proposed: string; proposedHash: string; base: string | null; topology: string; rule: TrustRule | null } +interface Payload { input: Prepare; reviewId: string; proposed: string; proposedHash: string; base: string | null; topology: string; rule: TrustRule | null; githubIdentity?: TrustGitHubIdentity } interface Row { principal_id: string; brain_id: string; authority: string; expires_at: number; retain_until: number; payload: string; stage: string; proof: string | null; receipt: string } const topology = (root: string) => [root, join(root, "context"), join(root, "context/policies"), join(root, "context/policies/governance.md")].map((path, i) => { const stat = lstatSync(path, { throwIfNoEntry: false }); @@ -78,7 +79,8 @@ export function createTrustSettings(options: { /** Null unless the current password-mode human principal remains usable. The * fingerprint includes credential/lifetime identity, never a body/channel claim. */ authority(principalId: string): string | null; - observe(operationId: string, publish: () => void): Promise; + observe(operationId: string, publish: () => void | Promise): Promise; + github?: ReturnType; now?: () => number; /** Host-only deterministic crash/race injection, never wired from HTTP. */ checkpoint?(stage: string): void | Promise; @@ -86,6 +88,8 @@ export function createTrustSettings(options: { let root: string; try { root = realpathSync(options.root); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; root = resolve(options.root); } const brain = hash(root); + const capabilities = { ...TRUST_RUNTIME_CAPABILITIES, repositoryIdentity: !!options.github, + readOnlyReason: "Runtime trust enforcement is unavailable" }; const call = procedureCaller(options.db, writes, undefined, options.writer), now = options.now ?? Date.now; const authority = (principal: string, expected?: string) => { const value = options.authority(principal); @@ -131,21 +135,32 @@ export function createTrustSettings(options: { if (r.stage === "file_published") receipt = { ...receipt, stage: "partial", publication: r.proof ? "proved" : "unknown", reason: "publication_recorded_completion_incomplete" }; const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); row(principal, request); return { receipt: current(receipt, payload, p), review: { reviewId: payload.reviewId, base: payload.base, proposed: payload.proposed, - diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at }, policy: p, capabilities }; + diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at, + repositoryIdentity: payload.githubIdentity ?? null, + includesFutureRepositories: payload.rule?.selector.kind === "github_owner" }, policy: p, capabilities }; }; return { /** Live trust-only projection for future admissions. Ordinary policy snapshots * remain owned by their admitted turn; this never mutates them. */ async snapshot() { return options.lock.withLock(BRAIN_LOCK_KEY, refresh); }, + /** Historical host publication evidence, not a current identity or source-trust grant. */ + async repositoryApproval(ruleId: string) { return options.lock.withLock(BRAIN_LOCK_KEY, async () => { + const p = await refresh(); + if (p.error) return null; + const rule = p.rules.find(value => value.id === ruleId); + if (!rule || (rule.selector.kind !== "github_owner" && rule.selector.kind !== "github_repository")) return null; + const row = options.db.query("SELECT selector,identity,proof FROM trust_settings_github_boundaries WHERE brain_id=? AND rule_id=?").get(brain, ruleId) as { selector: string; identity: string; proof: string } | null; + return row && row.selector === JSON.stringify(rule.selector) ? { identity: JSON.parse(row.identity) as TrustGitHubIdentity, proof: JSON.parse(row.proof) as unknown } : null; + }); }, async list(principal: string) { authority(principal); const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); authority(principal); return { ...p, origins: p.rules.filter(r => !r.selector.kind.startsWith("github_")), repositories: p.rules.filter(r => r.selector.kind.startsWith("github_")), capabilities }; }, read, - async prepare(principal: string, raw: unknown) { + async prepare(principal: string, raw: unknown, signal?: AbortSignal) { const auth = authority(principal), input = TrustPrepareSchema.parse(raw); if (process.platform !== "linux") throw new TrustSettingsError("unavailable", 503); // Names/IDs supplied by browsers cannot create repository identity proof. // Removal remains possible even while repository qualification is unavailable. - if (input.change.action !== "remove" && input.change.rule.selector.kind.startsWith("github_")) throw new TrustSettingsError("repository_identity_unavailable", 503); + if (input.change.action !== "remove" && input.change.rule.selector.kind.startsWith("github_") && !options.github) throw new TrustSettingsError("repository_identity_unavailable", 503); const request = await options.lock.withLock(BRAIN_LOCK_KEY, async () => { authority(principal, auth); const p = await refresh(); authority(principal, auth); if (p.error) throw new TrustSettingsError("unavailable", 503); @@ -163,8 +178,17 @@ export function createTrustSettings(options: { catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT" || p.policyHash !== null) throw error; } finally { target?.close(); } const proposed = edit(base, rules), requestId = id(), operationId = id(); + let githubIdentity: TrustGitHubIdentity | undefined; + if (change.action !== "remove" && (change.rule.selector.kind === "github_repository" || change.rule.selector.kind === "github_owner")) { + try { + const observed = await options.github!.resolve({ principalId: principal, selector: change.rule.selector, policyHash: p.policyHash, signal, + current: () => options.authority(principal) === auth }); + authority(principal, auth); observed.assertAuthority(); githubIdentity = observed.identity; + } catch { throw new TrustSettingsError("repository_identity_unavailable", 503); } + } if (Buffer.byteLength(JSON.stringify({ base, proposed, diff: exactDiff(base, proposed) })) > 196608) throw new TrustSettingsError("capacity", 503); - const payload: Payload = { input, reviewId: id(), proposed, proposedHash: hash(proposed), base, topology: identity, rule: change.action === "remove" ? null : change.rule }; + const payload: Payload = { input, reviewId: id(), proposed, proposedHash: hash(proposed), base, topology: identity, + rule: change.action === "remove" ? null : change.rule, ...(githubIdentity ? { githubIdentity } : {}) }; const receipt: Receipt = { version: 1, requestId, operationId, stage: "prepared", publication: "not_published", ruleId, publishedTrustRevision: null, currentRule: "unknown", enforcement: "unavailable", reason: null }; const inserted = await call("insert", { requestId, brainId: brain, principalId: principal, authority: auth, expires: now() + 900000, retain: now() + 86400000, @@ -174,7 +198,7 @@ export function createTrustSettings(options: { }); return read(principal, request); }, - async commit(principal: string, raw: unknown) { + async commit(principal: string, raw: unknown, signal?: AbortSignal) { const input: Commit = TrustCommitSchema.parse(raw); row(principal, input.requestId); await options.lock.withLock(BRAIN_LOCK_KEY, async () => { const r = row(principal, input.requestId), payload = JSON.parse(r.payload) as Payload; @@ -182,8 +206,11 @@ export function createTrustSettings(options: { if (r.stage !== "prepared") return; // Readback only, including uncertain writes. if (r.expires_at < now()) throw new TrustSettingsError("request_expired"); const receipt = JSON.parse(r.receipt) as Receipt; - let published = false, proved = false; const created: string[] = []; let target: AnchoredGovernancePolicy | undefined; - const save = (stage: string, proof: string | null = null) => call("stage", input.requestId, stage, JSON.stringify(receipt), proof, now()); + let published = false, proved = false, publicationOpen = true; + const created: string[] = []; let target: AnchoredGovernancePolicy | undefined; + const save = (stage: string, proof: string | null = null, + boundary?: { brain: string; ruleId: string; selector: string; identity: string }) => + call("stage", input.requestId, stage, JSON.stringify(receipt), proof, now(), boundary); try { const p = await refresh(); row(principal, input.requestId); if (p.error || p.revision !== payload.input.expectedTrustRevision) throw new TrustSettingsError("stale_revision"); @@ -192,19 +219,46 @@ export function createTrustSettings(options: { await save("writing"); await options.checkpoint?.("writing"); if (!matchesTopology(root, payload.topology, false)) throw new TrustSettingsError("stale_base"); target = openGovernancePolicyAnchored(root, { create: p.policyHash === null, created }); - const check = () => { row(principal, input.requestId); if (r.expires_at < now()) throw new TrustSettingsError("request_expired"); + let identityAuthority: (() => void) | undefined; + const check = () => { signal?.throwIfAborted(); + if (!publicationOpen) throw new TrustSettingsError("publication_failed"); + row(principal, input.requestId); identityAuthority?.(); if (r.expires_at < now()) throw new TrustSettingsError("request_expired"); if (!matchesTopology(root, payload.topology, true)) throw new TrustSettingsError("stale_base"); verifyGovernancePolicyAnchored(target!, p.policyHash); }; + let publication: Promise | undefined; await options.observe(receipt.operationId, () => { - publishProtectedPolicy(target!, Buffer.from(payload.proposed), p.policyHash, check, () => { published = true; }); + if (publication || !publicationOpen) throw new TrustSettingsError("request_conflict"); + publication = (async () => { + // The journal's own queue/observation waits precede the fresh + // metadata read. No further await separates its final authority + // fence from the synchronous descriptor-bound publication. + if (payload.rule && (payload.rule.selector.kind === "github_repository" || payload.rule.selector.kind === "github_owner")) { + if (!payload.githubIdentity || !options.github) throw new TrustSettingsError("repository_identity_unavailable", 503); + const observed = await options.github.resolve({ principalId: principal, selector: payload.rule.selector, policyHash: p.policyHash, signal, + current: () => publicationOpen && options.authority(principal) === r.authority && r.expires_at >= now() }); + if (JSON.stringify(observed.identity) !== JSON.stringify(payload.githubIdentity)) throw new TrustSettingsError("repository_identity_changed"); + identityAuthority = observed.assertAuthority; + } + identityAuthority?.(); + publishProtectedPolicy(target!, Buffer.from(payload.proposed), p.policyHash, check, () => { published = true; }); + })(); + // Preserve a rejected callback even if an older host observer + // forgets to await it; this invocation still joins it below. + void publication.catch(() => {}); + return publication; }); + if (!publication) throw new TrustSettingsError("publication_failed"); + await publication; + if (!published) throw new TrustSettingsError("publication_failed"); await options.checkpoint?.("renamed"); // The proof is written only after THIS invocation's atomic publication // and directory fsync, never inferred by comparing current bytes. receipt.stage = "file_published"; receipt.publication = "proved"; receipt.publishedTrustRevision = String(BigInt(p.revision) + 1n); await save("file_published", JSON.stringify({ operationId: receipt.operationId, principal, brain, authority: r.authority, - baseHash: p.policyHash, expectedTrustRevision: p.revision, publishedTrustRevision: receipt.publishedTrustRevision, reviewedBytesHash: payload.proposedHash })); proved = true; + baseHash: p.policyHash, expectedTrustRevision: p.revision, publishedTrustRevision: receipt.publishedTrustRevision, reviewedBytesHash: payload.proposedHash, + ...(payload.githubIdentity ? { githubIdentity: payload.githubIdentity } : {}) }), payload.githubIdentity && payload.rule + ? { brain, ruleId: payload.rule.id, selector: JSON.stringify(payload.rule.selector), identity: JSON.stringify(payload.githubIdentity) } : undefined); proved = true; await options.checkpoint?.("file_published"); const latest = await refresh(); row(principal, input.requestId); if (latest.policyHash === payload.proposedHash) receipt.publishedTrustRevision = latest.revision; @@ -212,11 +266,13 @@ export function createTrustSettings(options: { receipt.stage = "partial"; receipt.reason = "policy_saved_runtime_enforcement_unavailable"; await save("committed"); await options.checkpoint?.("committed"); } catch (error) { + publicationOpen = false; receipt.stage = proved ? "partial" : published ? "unknown" : "refused"; receipt.publication = proved ? "proved" : published ? "unknown" : "not_published"; - receipt.reason = error instanceof TrustSettingsError ? error.code : published ? "recording_failed" : "publication_failed"; + receipt.reason = error instanceof TrustSettingsError ? error.code : error instanceof ReferenceTransportError && !published + ? "repository_identity_unavailable" : published ? "recording_failed" : "publication_failed"; await save(receipt.stage); - } finally { target?.close(); if (!published) for (const path of created.reverse()) { try { rmdirSync(path); } catch { /* Concurrent content remains. */ } } } + } finally { publicationOpen = false; target?.close(); if (!published) for (const path of created.reverse()) { try { rmdirSync(path); } catch { /* Concurrent content remains. */ } } } }); return read(principal, input.requestId); }, diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index b57a012297..db84fe0eb0 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -674,9 +674,9 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }, /** Host Settings audit identity is retained by its durable operation store. * Observe user policy changes across existing turns without minting a turn. */ - observeSettingsPolicy(_operationId: string, approvedWrite: () => void): Promise { return held(async () => { + observeSettingsPolicy(_operationId: string, approvedWrite: () => void | Promise): Promise { return held(async () => { await observe(); - try { approvedWrite(); } finally { await observe(true); } + try { await approvedWrite(); } finally { await observe(true); } }); }, /** The caller retains approval/current-principal authority; this never revives a completed turn. */ observeUserPolicy(turnId: string, approvedWrite: () => void | Promise): Promise { return held(async () => { diff --git a/packages/ui-server/src/routes/trust-settings.ts b/packages/ui-server/src/routes/trust-settings.ts index 30c2437021..5c52ed3b23 100644 --- a/packages/ui-server/src/routes/trust-settings.ts +++ b/packages/ui-server/src/routes/trust-settings.ts @@ -7,6 +7,7 @@ import { readJsonBody } from "../middleware/body-limit.js"; import { TrustSettingsError, type TrustSettings } from "../brain/trust-settings.js"; export function createTrustSettingsRoutes(deps: { settings: TrustSettings; trustProxy: boolean }) { const routes = new Hono(); + const active = new Map(); let total = 0; routes.use("/trust-settings*", async (c, next) => { c.header("Cache-Control", "private, no-store"); if (!c.get("principal")) return c.json({ code: "unauthorized", reason: "Authentication required", retryable: false }, 401); @@ -20,7 +21,11 @@ export function createTrustSettingsRoutes(deps: { settings: TrustSettings; trust } catch { return c.json({ code: "unauthorized", reason: "Same-origin request required", retryable: false }, 403); } if (c.req.header("origin") !== expected) return c.json({ code: "unauthorized", reason: "Same-origin request required", retryable: false }, 403); } - await next(); + const principal = c.get("principal")!.id, count = active.get(principal) ?? 0; + if (count >= 32 || total >= 256) return c.json({ code: "busy", reason: "Too many Settings requests are active. Try again when one finishes.", retryable: true }, 503); + active.set(principal, count + 1); total++; + try { await next(); } + finally { total--; const remaining = active.get(principal)! - 1; if (remaining) active.set(principal, remaining); else active.delete(principal); } }); routes.onError((error, c) => error instanceof TrustSettingsError ? c.json({ code: error.code, reason: error.message, retryable: false }, error.status) : error instanceof ZodError ? c.json({ code: "request_conflict", reason: "Invalid request", retryable: false }, 400) @@ -29,7 +34,7 @@ export function createTrustSettingsRoutes(deps: { settings: TrustSettings; trust routes.get("/trust-settings/:request", async c => c.json(await deps.settings.read(c.get("principal")!.id, c.req.param("request")))); for (const action of ["prepare", "commit"] as const) routes.post(`/trust-settings/${action}`, requireJson(), async c => { const body = await readJsonBody(c, 65536).catch(() => null); if (body instanceof Response) return body; - return c.json(await deps.settings[action](c.get("principal")!.id, body)); + return c.json(await deps.settings[action](c.get("principal")!.id, body, c.req.raw.signal)); }); return routes; } diff --git a/packages/ui-server/tests/fixtures/trust-settings-crash.ts b/packages/ui-server/tests/fixtures/trust-settings-crash.ts index 98230da840..36e6eb0dbd 100644 --- a/packages/ui-server/tests/fixtures/trust-settings-crash.ts +++ b/packages/ui-server/tests/fixtures/trust-settings-crash.ts @@ -4,11 +4,21 @@ import { createUiDb } from "../../src/db/client.js"; import { openSqliteWriter } from "../../src/db/write-worker.js"; import { createTrustSettings } from "../../src/brain/trust-settings.js"; import { createKeyedLock } from "@schlessera/brain-ui-sdk/server"; +import { connect } from "node:net"; +import { createGitHubReferenceAccess } from "../../src/brain/github-reference-access.js"; +import { createTrustGitHubIdentity } from "../../src/brain/trust-github-identity.js"; const [root, at, request] = process.argv.slice(2) as [string, string, string]; const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); +const fixtureFile = Bun.file(join(root, "github-fixture.json")); +const metadata = await fixtureFile.exists() ? await fixtureFile.json() as { principalId: string; port: number; ca: string } : null; +const github = metadata ? createTrustGitHubIdentity({ root, access: createGitHubReferenceAccess({ db, brain: "ithaca-brain", + credentials: {}, transport: { async resolve() { throw new Error("No Git in Settings"); }, async fetch() { throw new Error("No Git in Settings"); }, async checkout() { throw new Error("No Git in Settings"); } }, + wireTransport: { ca: await Bun.file(metadata.ca).text(), lookup: async () => [{ address: "93.184.216.34", family: 4 }], + connect: (() => connect({ host: "127.0.0.1", port: metadata.port })) as typeof connect } }) }) : undefined; const settings = createTrustSettings({ root, db, writer, lock: createKeyedLock(), authority: () => "owner-epoch", + ...(github ? { github } : {}), observe: async (_id, publish) => publish(), checkpoint: stage => { if (stage === at) process.exit(77); } }); const review = JSON.parse(await Bun.file(join(root, "request.json")).text()); -if (at === "prepared") await settings.prepare("odysseus", review.input); -else await settings.commit("odysseus", { version: 1, requestId: request, reviewId: review.reviewId, reviewedBytesHash: review.reviewedBytesHash }); +if (at === "prepared") await settings.prepare(metadata?.principalId ?? "odysseus", review.input); +else await settings.commit(metadata?.principalId ?? "odysseus", { version: 1, requestId: request, reviewId: review.reviewId, reviewedBytesHash: review.reviewedBytesHash }); await writer.close(); db.close(); diff --git a/packages/ui-server/tests/trust-settings.test.ts b/packages/ui-server/tests/trust-settings.test.ts index aadca6ff7e..8b6623cf0c 100644 --- a/packages/ui-server/tests/trust-settings.test.ts +++ b/packages/ui-server/tests/trust-settings.test.ts @@ -15,6 +15,12 @@ import { authGuard, authRoutes, type AuthRuntime } from "../src/middleware/auth. import { resolveServerConfig } from "../src/config/env.js"; import { resolvePrincipal, isUsablePrincipal } from "../src/db/principals.js"; import type { AppEnv } from "../src/app-env.js"; +import { connect } from "node:net"; +import { fixtureTls } from "./fixtures/fixture-tls.js"; +import { createGitHubReferenceAccess } from "../src/brain/github-reference-access.js"; +import { createTrustGitHubIdentity } from "../src/brain/trust-github-identity.js"; +import { createPrincipal, revokePrincipal } from "../src/db/principals.js"; +import { createReferenceGrant, revokeReferenceGrant } from "../src/db/reference-grants.js"; const cleanup: (() => void | Promise)[] = []; afterEach(async () => { for (const f of cleanup.splice(0).reverse()) await f(); }); const initial = "---\nschema_version: 1\n# Keep ordinary configuration\nprofiles: {interactive: governed}\nbudgets: {turn: {block_usd: 17}}\n---\nThe voyage policy.\n"; @@ -28,7 +34,7 @@ async function fixture(patch: Partial[0]> const db = createUiDb(join(root, "ui.db")), writer = openSqliteWriter(db); cleanup.push(async () => { await writer.close(); db.close(); }); const lock = createKeyedLock(); let auth: string | null = "owner-epoch"; const observations: string[] = []; const options = { root, db, writer, lock, authority: (id: string) => id === "odysseus" ? auth : null, - observe: async (id: string, publish: () => void) => { observations.push(id); publish(); }, ...patch }; + observe: async (id: string, publish: () => void | Promise) => { observations.push(id); await publish(); }, ...patch }; const settings = createTrustSettings(options); const prepare = async (change: unknown = { action: "create", rule }) => { const p = await settings.list("odysseus"); return settings.prepare("odysseus", { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change }); }; @@ -195,3 +201,222 @@ test("real process death after prepared commit retains a readable draft and no f expect((await f.settings.read("odysseus", row.request_id)).receipt.stage).toBe("prepared"); expect(readFileSync(f.path, "utf8")).toBe(initial); }); + +const repositoryRule = { ...rule, id: "ithaca-source", selector: { kind: "github_repository" as const, host: "github.com" as const, + owner: "odysseus", repository: "ithaca", repositoryId: "101" } }; +const ownerRule = { ...rule, id: "ithaca-owner", selector: { kind: "github_owner" as const, host: "github.com" as const, owner: "odysseus", ownerId: "201" } }; + +async function githubFixture(patch: Partial[0]> = {}) { + const f = await fixture(), owner = createPrincipal(f.db, { authMethod: "password", label: "Penelope", ttlSeconds: 3600 }); + const state = { owner: "odysseus", ownerId: "201", repository: "ithaca", repositoryId: "101", private: false, status: 200 }; + const requests: { path: string; authorization: string | null }[] = []; + const tls = fixtureTls(join(f.root, "tls"), ["api.github.com"]); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, tls: { cert: tls.cert, key: tls.key }, fetch(request) { + const path = new URL(request.url).pathname, authorization = request.headers.get("authorization"); + requests.push({ path, authorization }); + if (state.status !== 200) return new Response(null, { status: state.status }); + if (path.startsWith("/users/")) return Response.json({ id: state.ownerId, login: state.owner, type: "User", + url: `https://api.github.com/users/${state.owner}`, html_url: `https://github.com/${state.owner}` }); + if (state.private && !authorization) return new Response(null, { status: 404 }); + return Response.json({ id: state.repositoryId, owner: { id: state.ownerId, login: state.owner }, name: state.repository, + full_name: `${state.owner}/${state.repository}`, clone_url: `https://github.com/${state.owner}/${state.repository}.git`, + url: `https://api.github.com/repos/${state.owner}/${state.repository}`, private: state.private }); + } }); + cleanup.push(() => server.stop(true)); + const access = createGitHubReferenceAccess({ db: f.db, brain: "ithaca-brain", credentials: { GITHUB_TOKEN: "odysseus-fixture-token" }, + transport: { async resolve() { throw new Error("Settings cannot discover Git refs"); }, async fetch() { throw new Error("Settings cannot fetch Git"); }, + async checkout() { throw new Error("Settings cannot check out source"); } }, + wireTransport: { ca: readFileSync(tls.ca, "utf8"), lookup: async () => [{ address: "93.184.216.34", family: 4 }], + connect: (() => connect({ host: "127.0.0.1", port: server.port! })) as typeof connect } }); + const github = createTrustGitHubIdentity({ root: f.root, access }); + const options = { ...f.options, github, authority: (id: string) => { + const p = resolvePrincipal(f.db, id); + return id === owner.id && p?.kind === "owner" && isUsablePrincipal(p, Date.now()) ? "owner-epoch" : null; + }, ...patch }; + const settings = createTrustSettings(options); + const prepare = async (change: unknown = { action: "create", rule: repositoryRule }) => { + const p = await settings.list(owner.id); + return settings.prepare(owner.id, { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change }); + }; + const commit = (draft: Awaited>) => settings.commit(owner.id, { version: 1, requestId: draft.receipt.requestId, + reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + const grant = () => createReferenceGrant(f.db, { brain: "ithaca-brain", principalId: owner.id, createdBy: owner.id, + repositoryPrefix: "https://github.com/odysseus", credential: "GITHUB_TOKEN", metadataCredentialRecipient: "https://api.github.com", now: Date.now() }); + return { ...f, owner, options, settings, github, state, requests, prepare, commit, grant, + childMetadata: { principalId: owner.id, port: server.port!, ca: tls.ca } }; +} + +for (const selected of [repositoryRule, ownerRule]) test(`actual TLS metadata and protected publication support ${selected.selector.kind} CRUD without a turn`, async () => { + const f = await githubFixture(); + const pending = f.prepare({ action: "create", rule: selected }).then(draft => f.commit(draft)); + await expect(pending, "SETTINGS_GITHUB_CRUD_USES_HOST_METADATA_AND_REAL_PUBLICATION").resolves.toMatchObject({ receipt: { publication: "proved", currentRule: "present", enforcement: "unavailable" } }); + const saved = await pending, approval = await f.settings.repositoryApproval(selected.id); + expect(approval, "SETTINGS_APPROVED_OWNER_COMES_FROM_PROVED_PUBLICATION").toMatchObject({ + identity: { selector: selected.selector, ownerId: "201" }, proof: { reviewedBytesHash: saved.review.reviewedBytesHash, principal: f.owner.id } }); + expect(saved.review.includesFutureRepositories).toBe(selected.selector.kind === "github_owner"); + expect(f.requests).toHaveLength(2); expect(f.requests.every(request => request.authorization === null)).toBe(true); + const edited = await f.prepare({ action: "edit", rule: { ...selected, label: "The home harbor" } }); + expect((await f.commit(edited)).receipt.publication).toBe("proved"); + expect((await f.settings.read(f.owner.id, saved.receipt.requestId)).receipt.currentRule).toBe("changed"); + const observed = f.requests.length; f.state.status = 500; + await f.commit(await f.prepare({ action: "remove", ruleId: selected.id })); + expect(f.requests).toHaveLength(observed); expect(await f.settings.repositoryApproval(selected.id)).toBeNull(); + expect((await f.settings.read(f.owner.id, saved.receipt.requestId)).receipt.currentRule).toBe("removed"); + expect(f.db.query("SELECT count(*) n FROM sessions").get()).toEqual({ n: 0 }); + expect(f.db.query("SELECT count(*) n FROM policy_proposals").get()).toEqual({ n: 0 }); +}); + +for (const change of ["repository_id", "owner_id", "rename", "transfer", "unavailable"] as const) + test(`a reviewed repository cannot publish after ${change} metadata changes`, async () => { + const f = await githubFixture(), draft = await f.prepare(); + expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + if (change === "repository_id") f.state.repositoryId = "102"; + else if (change === "owner_id") f.state.ownerId = "202"; + else if (change === "rename") f.state.repository = "fleet"; + else if (change === "transfer") f.state.owner = "penelope"; + else f.state.status = 500; + const result = await f.commit(draft); + expect(result.receipt.publication, "SETTINGS_METADATA_CHANGE_CANNOT_INHERIT_REVIEW").toBe("not_published"); + expect(readFileSync(f.path, "utf8")).toBe(initial); expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + expect(result.review.proposed).toBe(draft.review.proposed); + }); + +test("a private Settings publication retains the actual selected grant through its final fence", async () => { + const f = await githubFixture(); f.state.private = true; const grant = f.grant(); + const draft = await f.prepare(); + const settings = createTrustSettings({ ...f.options, github: { async resolve(input) { + const observed = await f.github.resolve(input); + revokeReferenceGrant(f.db, { brain: "ithaca-brain", principalId: f.owner.id, id: grant.id, now: Date.now() }); + return observed; + } } }); + const result = await settings.commit(f.owner.id, { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, + reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(result.receipt.publication, "SETTINGS_FINAL_GRANT_FENCE_PRECEDES_PROTECTED_PUBLICATION").toBe("not_published"); + expect(readFileSync(f.path, "utf8")).toBe(initial); expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + expect(f.requests.map(request => request.authorization)).toEqual([null, "Bearer odysseus-fixture-token", null, "Bearer odysseus-fixture-token"]); +}); + +test("equal policy bytes and prepared metadata are not approved-owner publication evidence", async () => { + const f = await githubFixture(), draft = await f.prepare(); + writeFileSync(f.path, draft.review.proposed); + expect((await f.settings.snapshot()).rules).toEqual([repositoryRule]); + expect(await f.settings.repositoryApproval(repositoryRule.id), "SETTINGS_EQUAL_BYTES_DO_NOT_PROVE_OWNER_APPROVAL").toBeNull(); + expect((await f.commit(draft)).receipt.publication).toBe("not_published"); +}); + +test("publication proof and owner-boundary recording commit atomically and survive operation pruning", async () => { + const f = await githubFixture(), draft = await f.prepare(); + f.db.exec("CREATE TRIGGER reject_boundary BEFORE INSERT ON trust_settings_github_boundaries BEGIN SELECT RAISE(ABORT,'boundary failed'); END"); + const result = await f.commit(draft); + expect(result.receipt.publication, "SETTINGS_BOUNDARY_FAILURE_RETAINS_UNKNOWN_PUBLICATION").toBe("unknown"); + expect(await f.settings.repositoryApproval(repositoryRule.id)).toBeNull(); + expect((await f.commit(draft)).receipt.publication).toBe("unknown"); + f.db.exec("DROP TRIGGER reject_boundary"); + const corrected = await f.prepare({ action: "edit", rule: { ...repositoryRule, label: "The home harbor" } }); + expect((await f.commit(corrected)).receipt.publication).toBe("proved"); + const before = await f.settings.repositoryApproval(repositoryRule.id); expect(before).not.toBeNull(); + f.db.exec("DELETE FROM trust_settings_operations"); + const restarted = createTrustSettings(f.options); + expect(await restarted.repositoryApproval(repositoryRule.id), "SETTINGS_OWNER_APPROVAL_SURVIVES_BOUNDED_RECEIPT_PRUNING").toEqual(before); +}); + +test("an observer that never invokes its publication callback cannot manufacture proof", async () => { + const f = await fixture({ observe: async () => {} }), draft = await f.prepare(); + expect((await f.commit(draft)).receipt.publication, "SETTINGS_MISSING_PUBLICATION_CALLBACK_IS_NOT_PROOF").toBe("not_published"); + expect(readFileSync(f.path, "utf8")).toBe(initial); +}); + +for (const stage of ["writing", "renamed", "file_published", "committed"]) + test(`GitHub owner-boundary recovery after real process death at ${stage} uses durable publication proof`, async () => { + const f = await githubFixture(), draft = await f.prepare(); + writeFileSync(join(f.root, "request.json"), JSON.stringify(draft.review)); + writeFileSync(join(f.root, "github-fixture.json"), JSON.stringify(f.childMetadata)); + const child = Bun.spawn([process.execPath, join(import.meta.dir, "fixtures/trust-settings-crash.ts"), f.root, stage, draft.receipt.requestId], { stdout: "pipe", stderr: "pipe" }); + const [code, stderr] = await Promise.all([child.exited, new Response(child.stderr).text()]); + expect({ code, stderr }).toEqual({ code: 77, stderr: "" }); + const recovered = createTrustSettings(f.options), result = await recovered.read(f.owner.id, draft.receipt.requestId); + const proved = stage === "file_published" || stage === "committed"; + expect(result.receipt.publication).toBe(proved ? "proved" : "unknown"); + const approval = await recovered.repositoryApproval(repositoryRule.id); + expect(approval !== null, "SETTINGS_CRASH_OWNER_APPROVAL_REQUIRES_DURABLE_PROOF").toBe(proved); + if (proved) expect(approval).toMatchObject({ identity: { ownerId: "201", selector: repositoryRule.selector }, + proof: { reviewedBytesHash: draft.review.reviewedBytesHash, principal: f.owner.id } }); + const count = f.requests.length; + expect((await f.commit(draft)).receipt.publication).toBe(result.receipt.publication); + expect(f.requests, "SETTINGS_CRASH_REPLAY_NEVER_REPEATS_METADATA_OR_PUBLICATION").toHaveLength(count); + }); + +test("metadata after a journal wait rechecks the live owner before touching the policy", async () => { + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await githubFixture({ observe: async (_id, publish) => { ready(); await held; await publish(); } }), draft = await f.prepare(); + const pending = f.commit(draft); + try { + await reached; revokePrincipal(f.db, f.owner.id, Date.now()); release(); + const rejected = await pending.then(() => null, error => error); + expect(rejected, "SETTINGS_REVOKED_OWNER_AFTER_JOURNAL_WAIT_CANNOT_PUBLISH").toMatchObject({ message: "unauthorized" }); + expect(f.requests).toHaveLength(1); expect(readFileSync(f.path, "utf8")).toBe(initial); + expect(f.db.query("SELECT count(*) n FROM trust_settings_github_boundaries").get()).toEqual({ n: 0 }); + } finally { release(); await pending.catch(() => {}); } +}); + +test("real HTTP GitHub Settings CRUD compares browser IDs with fresh host metadata", async () => { + const f = await githubFixture(), password = "ithaca-settings-test", secret = "fictional-cookie-secret-for-ithaca-tests"; + const config = resolveServerConfig({ AUTH_MODE: "password", BRAIN_UI_PASSWORD_HASH: await Bun.password.hash(password), COOKIE_SECRET: secret }); + const auth: AuthRuntime = { ...config.auth, host: "127.0.0.1" }; + const settings = createTrustSettings({ ...f.options, authority: id => { + const p = resolvePrincipal(f.db, id); + return p?.kind === "owner" && isUsablePrincipal(p, Date.now()) ? "owner-epoch" : null; + } }); + const app = new Hono(); app.route("/api", authRoutes("password", auth, { db: f.db, revoker: { revokePrincipals() {} } })); + app.use("/api/*", authGuard("password", auth, f.db)); + app.route("/api", createTrustSettingsRoutes({ settings, trustProxy: false })); + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch: app.fetch }); cleanup.push(() => server.stop(true)); + const base = `http://127.0.0.1:${server.port}`; + const login = await fetch(`${base}/api/auth/login`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ password }) }); + expect(login.status).toBe(200); const cookie = login.headers.get("set-cookie")!.split(";")[0]!; + const request = (path: string, body?: unknown) => fetch(`${base}/api/trust-settings${path}`, { method: body ? "POST" : "GET", + headers: { cookie, "content-type": "application/json", origin: base }, ...(body ? { body: JSON.stringify(body) } : {}) }); + const p = await (await request("")).json() as { revision: string; policyHash: string | null }; + const body = { version: 1, expectedTrustRevision: p.revision, expectedPolicyHash: p.policyHash, change: { action: "create", rule: repositoryRule } }; + const forged = await request("/prepare", { ...body, change: { action: "create", rule: { ...repositoryRule, selector: { ...repositoryRule.selector, repositoryId: "999" } } } }); + expect(forged.status, "SETTINGS_HTTP_BROWSER_ID_CANNOT_SELF_VERIFY").toBe(503); + const prepared = await request("/prepare", body); expect(prepared.status).toBe(200); + const draft = await prepared.json() as Awaited>; + expect(draft.review.repositoryIdentity).toMatchObject({ ownerId: "201", selector: repositoryRule.selector }); + const committed = await request("/commit", { version: 1, requestId: draft.receipt.requestId, reviewId: draft.review.reviewId, reviewedBytesHash: draft.review.reviewedBytesHash }); + expect(committed.status).toBe(200); expect((await committed.json() as typeof draft).receipt.publication).toBe("proved"); + expect(f.requests).toHaveLength(3); +}); + +test("the actual journal retains its Settings window through asynchronous publication", async () => { + const f = await fixture(), objects = mkdtempSync(join(f.root, "../objects-")); cleanup.push(() => rmSync(objects, { recursive: true, force: true })); + const native = createNativeJournalFixture(f.root, objects); cleanup.push(() => native.close()); + const journal = createTurnJournal(f.db, { nativeManager: native.manager, brainPath: f.root, dbPath: join(f.root, "ui.db"), objectsRoot: objects }); cleanup.push(() => journal.close()); + let ready!: () => void, release!: () => void, timer: ReturnType | undefined; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const first = journal.observeSettingsPolicy("ithaca-first", async () => { ready(); await held; }); + await reached; + const second = journal.observeSettingsPolicy("ithaca-second", () => {}); + try { + const result = await Promise.race([second.then(() => "advanced"), new Promise(resolve => { timer = setTimeout(() => resolve("held"), 1000); })]); + expect(result, "SETTINGS_JOURNAL_WINDOW_INCLUDES_ASYNC_PUBLICATION").toBe("held"); + } finally { if (timer) clearTimeout(timer); release(); await Promise.allSettled([first, second]); } +}); + +test("Settings HTTP admission bounds queued lock waiters and recovers when requests finish", async () => { + const f = await githubFixture(), app = new Hono(); + app.use("*", async (c, next) => { c.set("principal", f.owner); await next(); }); + app.route("/api", createTrustSettingsRoutes({ settings: f.settings, trustProxy: false })); + const release = await f.lock.acquire(BRAIN_LOCK_KEY); + const pending = Array.from({ length: 32 }, () => app.request("http://localhost/api/trust-settings")); + let timer: ReturnType | undefined; + const excess = app.request("http://localhost/api/trust-settings"); + try { + const result = await Promise.race([Promise.resolve(excess).then(response => response.status), new Promise(resolve => { timer = setTimeout(() => resolve(null), 1000); })]); + expect(result, "SETTINGS_HTTP_QUEUE_REFUSES_BEFORE_ANOTHER_LOCK_WAIT").toBe(503); + expect(await (await excess).json()).toMatchObject({ code: "busy", retryable: true }); + } finally { if (timer) clearTimeout(timer); release(); await Promise.allSettled([...pending, excess]); } + expect((await app.request("http://localhost/api/trust-settings")).status, "SETTINGS_HTTP_BUSY_CLEARS_WHEN_WAITERS_DRAIN").toBe(200); + expect(f.requests).toEqual([]); +}); From 84fb7722fac887722aa86329f52bc34e62274493 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:44:52 +0000 Subject: [PATCH 8/9] CONTRACT: fix(ui-server): attribute only synchronous Settings publication --- api-report/ui-server.txt | 4 +- docs/decisions/governed-writable-workers.md | 2 +- docs/decisions/journal-database.md | 2 +- docs/integration-contract/package-api.md | 5 ++- .../ui-server/src/brain/trust-settings.ts | 14 +++--- packages/ui-server/src/brain/turn-journal.ts | 30 +++++++++++-- packages/ui-server/tests/turn-journal.test.ts | 43 +++++++++++++++++++ 7 files changed, 85 insertions(+), 15 deletions(-) diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index e3630fc0ae..f0ea66c3d4 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -2658,8 +2658,8 @@ signatures (every public export and the types it is made of) isHeld(): boolean; maintain: () => Promise; observe(): Promise; - observeSettingsPolicy(_operationId: string, approvedWrite: () => Promise | void): Promise; - observeUserPolicy(turnId: string, approvedWrite: () => Promise | void): Promise; + observeSettingsPolicy(_operationId: string, operation: (publish?: (write: () => void) => Promise) => Promise | void): Promise; + observeUserPolicy(turnId: string, approvedWrite: () => void): Promise; onObservation(observer: (turnId: string, facts: { changedPaths: number; observedBytes: number; diff --git a/docs/decisions/governed-writable-workers.md b/docs/decisions/governed-writable-workers.md index b6b7afdc65..08e7d87cc5 100644 --- a/docs/decisions/governed-writable-workers.md +++ b/docs/decisions/governed-writable-workers.md @@ -4767,7 +4767,7 @@ memory completion of the earlier 0.42.0 steering slice, not a widening of memory providers or a claim of capturing intervening external writes. The copy-out boundary is `const write`, `packages/ui-backend-claude/src/worker-state.ts:210-224`; retention/finalization is `persistClaudeMemory`, -`packages/ui-server/src/brain/turn-journal.ts:741-771`; destination-bound recovery +`packages/ui-server/src/brain/turn-journal.ts:763-793`; destination-bound recovery is `const target`, `packages/ui-server/src/brain/turn-revert.ts:113-123`. ### Concurrent edits diff --git a/docs/decisions/journal-database.md b/docs/decisions/journal-database.md index 8c165d7cb7..67a2ac912c 100644 --- a/docs/decisions/journal-database.md +++ b/docs/decisions/journal-database.md @@ -97,7 +97,7 @@ that no pre-charge covers. The evidence is on the issue. readers understand the arrays until then, and an empty legacy array stays "no set recorded". The brain's current set is the one the most recent complete, inventoried turn recorded - (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:822-828`). + (`configurationCoverage(): ConfigurationCoverageRead`, `packages/ui-server/src/brain/turn-journal.ts:844-850`). The sets table is an ordinary rowid table, as every journal table is: the operational backup copies and compares journal rows in rowid order. diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index 32961ec082..ac8d9b271a 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5640,7 +5640,10 @@ runtime enforcement. Current responses use `partial` for saved policy because of historical publication proof. No removal receipt claims an enforcing fence. No agent turn, provider message or ordinary governance snapshot is changed. The journal awaits asynchronous metadata and publication before releasing its -Settings observation window; a missing publication callback cannot produce proof. +Settings observation window. It records intervening changes with their ordinary attribution before +entering the synchronous approved write, and a failed lookup or a callback that +publishes nothing cannot grant user-policy attribution. A missing publication +callback cannot produce proof. The live trust projection retains last-valid rules on invalid policy, reports an error, and increments its decimal uint64 revision only for trust-list changes. Exhausted revisions refuse both new reviews and publication of retained reviews diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index b48516217c..4dc8960d56 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -79,7 +79,7 @@ export function createTrustSettings(options: { /** Null unless the current password-mode human principal remains usable. The * fingerprint includes credential/lifetime identity, never a body/channel claim. */ authority(principalId: string): string | null; - observe(operationId: string, publish: () => void | Promise): Promise; + observe(operationId: string, operation: (publish?: (write: () => void) => Promise) => void | Promise): Promise; github?: ReturnType; now?: () => number; /** Host-only deterministic crash/race injection, never wired from HTTP. */ @@ -226,12 +226,12 @@ export function createTrustSettings(options: { if (!matchesTopology(root, payload.topology, true)) throw new TrustSettingsError("stale_base"); verifyGovernancePolicyAnchored(target!, p.policyHash); }; let publication: Promise | undefined; - await options.observe(receipt.operationId, () => { + await options.observe(receipt.operationId, (publish = async write => { write(); }) => { if (publication || !publicationOpen) throw new TrustSettingsError("request_conflict"); publication = (async () => { // The journal's own queue/observation waits precede the fresh - // metadata read. No further await separates its final authority - // fence from the synchronous descriptor-bound publication. + // metadata read. Journal attribution then checkpoints intervening + // edits before the synchronous authority/publication fence. if (payload.rule && (payload.rule.selector.kind === "github_repository" || payload.rule.selector.kind === "github_owner")) { if (!payload.githubIdentity || !options.github) throw new TrustSettingsError("repository_identity_unavailable", 503); const observed = await options.github.resolve({ principalId: principal, selector: payload.rule.selector, policyHash: p.policyHash, signal, @@ -239,8 +239,10 @@ export function createTrustSettings(options: { if (JSON.stringify(observed.identity) !== JSON.stringify(payload.githubIdentity)) throw new TrustSettingsError("repository_identity_changed"); identityAuthority = observed.assertAuthority; } - identityAuthority?.(); - publishProtectedPolicy(target!, Buffer.from(payload.proposed), p.policyHash, check, () => { published = true; }); + await publish(() => { + identityAuthority?.(); + publishProtectedPolicy(target!, Buffer.from(payload.proposed), p.policyHash, check, () => { published = true; }); + }); })(); // Preserve a rejected callback even if an older host observer // forgets to await it; this invocation still joins it below. diff --git a/packages/ui-server/src/brain/turn-journal.ts b/packages/ui-server/src/brain/turn-journal.ts index db84fe0eb0..6342fb7640 100644 --- a/packages/ui-server/src/brain/turn-journal.ts +++ b/packages/ui-server/src/brain/turn-journal.ts @@ -674,16 +674,38 @@ export function createTurnJournal(db: Database, options: TurnJournalOptions) { }, /** Host Settings audit identity is retained by its durable operation store. * Observe user policy changes across existing turns without minting a turn. */ - observeSettingsPolicy(_operationId: string, approvedWrite: () => void | Promise): Promise { return held(async () => { + observeSettingsPolicy(_operationId: string, operation: (publish?: (write: () => void) => Promise) => void | Promise): Promise { return held(async () => { await observe(); - try { await approvedWrite(); } finally { await observe(true); } + let open = true, publication: Promise | undefined; + try { + await operation(write => { + if (!open || publication) throw new JournalStorageUnavailable("Settings publication window is no longer available"); + publication = (async () => { + // Metadata waits are not approved writes. Attribute their changes + // before entering the synchronous descriptor publication boundary. + await observe(); + if (!open) throw new JournalStorageUnavailable("Settings publication window ended"); + let completed = false; + try { write(); completed = true; } + finally { await observe(completed); } + })(); + void publication.catch(() => {}); + return publication; + }); + await publication; + } finally { + open = false; + await publication?.catch(() => {}); + await observe(); + } }); }, /** The caller retains approval/current-principal authority; this never revives a completed turn. */ - observeUserPolicy(turnId: string, approvedWrite: () => void | Promise): Promise { return held(async () => { + observeUserPolicy(turnId: string, approvedWrite: () => void): Promise { return held(async () => { if (!active.has(turnId) || summary(turnId).state !== "recording") throw new JournalStorageUnavailable("approved policy write requires an active complete observation window"); await observe(); if (summary(turnId).state !== "recording") throw new JournalStorageUnavailable("policy observation became incomplete before the approved write"); - try { await approvedWrite(); } finally { await observe(true); } + let completed = false; + try { approvedWrite(); completed = true; } finally { await observe(completed); } }); }, finish(turnId: string) { return held(async timing => { if (!active.has(turnId)) { if (failedAdmissions.has(turnId)) await finalizeRefusedAdmission(turnId); return; } diff --git a/packages/ui-server/tests/turn-journal.test.ts b/packages/ui-server/tests/turn-journal.test.ts index 7e578168f2..67e6554388 100644 --- a/packages/ui-server/tests/turn-journal.test.ts +++ b/packages/ui-server/tests/turn-journal.test.ts @@ -432,6 +432,49 @@ test("approved policy writes retain user attribution in the original active wind } finally { await f.close(); } }); +test("a failed asynchronous Settings operation cannot approve concurrent policy edits", async () => { + const f = fixture(); + try { + mkdirSync(join(f.brain, "context/policies"), { recursive: true }); + const policy = join(f.brain, "context/policies/governance.md"); + writeFileSync(policy, "Athena's original policy\n"); + await f.begin("odysseus"); + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const pending = f.journal.observeSettingsPolicy("ithaca-rejected", async () => { ready(); await held; throw new Error("metadata unavailable"); }); + await reached; + writeFileSync(policy, "Unapproved policy during metadata lookup\n"); release(); + await expectRejection(pending, "metadata unavailable"); + const change = f.journal.details("ithaca", "odysseus")!.changes.find(change => change.path === "context/policies/governance.md"); + expect(change, "SETTINGS_FAILED_ASYNC_LOOKUP_CANNOT_APPROVE_CONCURRENT_EDIT").toMatchObject({ class: "content", actor: "agent" }); + expect(queryGovernanceEvents(f.db, { turnId: "odysseus", kinds: ["steering_change"], limit: 100 })).toHaveLength(0); + await f.journal.finish("odysseus"); + } finally { await f.close(); } +}); + +for (const publishPolicy of [false, true]) test(`Settings metadata waits retain normal attribution before publication=${publishPolicy}`, async () => { + const f = fixture(); + try { + mkdirSync(join(f.brain, "context/policies"), { recursive: true }); + const policy = join(f.brain, "context/policies/governance.md"); + writeFileSync(policy, "Athena's original policy\n"); + await f.begin("odysseus"); + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const pending = f.journal.observeSettingsPolicy("ithaca-reviewed", async publish => { + ready(); await held; + if (publishPolicy) await publish!(() => writeFileSync(policy, "Odysseus approves this policy\n")); + }); + await reached; writeFileSync(policy, "Unapproved edit during metadata lookup\n"); release(); await pending; + const changes = f.journal.details("ithaca", "odysseus")!.changes.filter(change => change.path === "context/policies/governance.md"); + expect(changes.map(change => ({ actor: change.actor, class: change.class })), "SETTINGS_ONLY_SYNCHRONOUS_PUBLICATION_IS_USER_POLICY").toEqual([ + { actor: "agent", class: "content" }, ...(publishPolicy ? [{ actor: "user" as const, class: "policy" as const }] : []), + ]); + expect(queryGovernanceEvents(f.db, { turnId: "odysseus", kinds: ["steering_change"], limit: 100 })).toHaveLength(0); + await f.journal.finish("odysseus"); + } finally { await f.close(); } +}); + test("actual journal classifies steering and local transitive configuration separately from content and policy", async () => { const f = fixture(); try { From 0e987664acb14ca5c3e831b371605d2b19d936a9 Mon Sep 17 00:00:00 2001 From: Alain Schlesser Date: Fri, 20 Nov 2026 13:51:15 +0000 Subject: [PATCH 9/9] CONTRACT: fix(ui-server): read trust receipts after acquiring the publication lock --- docs/integration-contract/package-api.md | 3 ++- .../ui-server/src/brain/trust-settings.ts | 21 +++++++++++-------- .../ui-server/tests/trust-settings.test.ts | 15 +++++++++++++ 3 files changed, 29 insertions(+), 10 deletions(-) diff --git a/docs/integration-contract/package-api.md b/docs/integration-contract/package-api.md index ac8d9b271a..3e829dc991 100644 --- a/docs/integration-contract/package-api.md +++ b/docs/integration-contract/package-api.md @@ -5637,7 +5637,8 @@ The receipt stages are `prepared|file_published|committed|partial|unknown|refuse runtime enforcement. Current responses use `partial` for saved policy because `enforcement:unavailable` remains truthful until the admission implementation. `currentRule:present|removed|changed|unknown` is refreshed on reads, independently -of historical publication proof. No removal receipt claims an enforcing fence. +of historical publication proof. Readback loads the durable operation and policy +projection within the same brain lock after any in-progress commit finishes. No removal receipt claims an enforcing fence. No agent turn, provider message or ordinary governance snapshot is changed. The journal awaits asynchronous metadata and publication before releasing its Settings observation window. It records intervening changes with their ordinary attribution before diff --git a/packages/ui-server/src/brain/trust-settings.ts b/packages/ui-server/src/brain/trust-settings.ts index 4dc8960d56..00bbcf2e25 100644 --- a/packages/ui-server/src/brain/trust-settings.ts +++ b/packages/ui-server/src/brain/trust-settings.ts @@ -129,15 +129,18 @@ export function createTrustSettings(options: { return { ...receipt, currentRule: p.error ? "unknown" : !rule ? "removed" : JSON.stringify(rule) === JSON.stringify(payload.rule) ? "present" : "changed" }; }; const read = async (principal: string, request: string) => { - const r = row(principal, request), payload = JSON.parse(r.payload) as Payload; - let receipt = JSON.parse(r.receipt) as Receipt; - if (r.stage === "writing") receipt = { ...receipt, stage: "unknown", publication: "unknown", reason: "publication_completion_unknown" }; - if (r.stage === "file_published") receipt = { ...receipt, stage: "partial", publication: r.proof ? "proved" : "unknown", reason: "publication_recorded_completion_incomplete" }; - const p = await options.lock.withLock(BRAIN_LOCK_KEY, refresh); row(principal, request); - return { receipt: current(receipt, payload, p), review: { reviewId: payload.reviewId, base: payload.base, proposed: payload.proposed, - diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at, - repositoryIdentity: payload.githubIdentity ?? null, - includesFutureRepositories: payload.rule?.selector.kind === "github_owner" }, policy: p, capabilities }; + row(principal, request); + return options.lock.withLock(BRAIN_LOCK_KEY, async () => { + const p = await refresh(); + const r = row(principal, request), payload = JSON.parse(r.payload) as Payload; + let receipt = JSON.parse(r.receipt) as Receipt; + if (r.stage === "writing") receipt = { ...receipt, stage: "unknown", publication: "unknown", reason: "publication_completion_unknown" }; + if (r.stage === "file_published") receipt = { ...receipt, stage: "partial", publication: r.proof ? "proved" : "unknown", reason: "publication_recorded_completion_incomplete" }; + return { receipt: current(receipt, payload, p), review: { reviewId: payload.reviewId, base: payload.base, proposed: payload.proposed, + diff: exactDiff(payload.base, payload.proposed), reviewedBytesHash: payload.proposedHash, expiresAt: r.expires_at, + repositoryIdentity: payload.githubIdentity ?? null, + includesFutureRepositories: payload.rule?.selector.kind === "github_owner" }, policy: p, capabilities }; + }); }; return { /** Live trust-only projection for future admissions. Ordinary policy snapshots diff --git a/packages/ui-server/tests/trust-settings.test.ts b/packages/ui-server/tests/trust-settings.test.ts index 8b6623cf0c..b531899344 100644 --- a/packages/ui-server/tests/trust-settings.test.ts +++ b/packages/ui-server/tests/trust-settings.test.ts @@ -56,6 +56,21 @@ test("real descriptor CRUD is exact, durable and creates no agent turn; readback expect(f.db.query("SELECT count(*) n FROM policy_proposals").get()).toEqual({ n: 0 }); expect((await f.settings.list("odysseus")).capabilities.repositoryRules).toBe(false); }); +for (const stage of ["writing", "file_published"]) test(`readback waiting on a ${stage} commit returns its completed durable receipt`, async () => { + let ready!: () => void, release!: () => void; + const reached = new Promise(resolve => { ready = resolve; }), held = new Promise(resolve => { release = resolve; }); + const f = await fixture({ checkpoint: async value => { if (value === stage) { ready(); await held; } } }), draft = await f.prepare(); + const pendingCommit = f.commit(draft); + try { + await reached; + const pendingRead = f.settings.read("odysseus", draft.receipt.requestId); + release(); + const [read, committed] = await Promise.all([pendingRead, pendingCommit]); + expect(read.receipt, "SETTINGS_READ_AFTER_LOCK_USES_COMPLETED_DURABLE_RECEIPT").toEqual(committed.receipt); + expect(read.receipt.publication).toBe("proved"); + } finally { release(); await pendingCommit.catch(() => {}); } +}); + test("changed request, foreign principal, arbitrary handles and expired reviews cannot replay", async () => { let now = 1000; const f = await fixture({ now: () => now }), draft = await f.prepare(); await expect(f.commit(draft, { reviewedBytesHash: "a".repeat(64) })).rejects.toThrow("request_conflict");