diff --git a/.changeset/3798-github-write-tools.md b/.changeset/3798-github-write-tools.md new file mode 100644 index 0000000000..d20274d2c5 --- /dev/null +++ b/.changeset/3798-github-write-tools.md @@ -0,0 +1,9 @@ +--- +"@schlessera/brain-common": minor +"@schlessera/brain": minor +"@schlessera/brain-ui-server": minor +"@schlessera/brain-backend-claude": minor +"@schlessera/brain-backend-pi": minor +--- + +Hosted chat turns can file GitHub issues and comment on them through the two host write tools, `brain_github_issue_create` and `brain_github_issue_comment` (#3798). Both backends now list them in every interactive session's fixed roster, after the read tools, and in no autonomous roster. A write goes only to a repository the governance policy lists under the new key `outward.github.repositories`, as `owner/repo` or `owner/*` (compared without case); any other repository is refused before an approval card is shown, and an absent or empty list allows no writes. A malformed entry makes the policy invalid. Inside the list, the user approves each write on one card showing exactly what will be sent, and it is sent once; a denial, an edited approval or a voice turn sends nothing. Every decision is recorded as an outward action and listed as irreversible in the turn journal. `brain policy check --json` reports the new key under `effective.outward.github.repositories`. diff --git a/api-report/common.txt b/api-report/common.txt index 8885ada7eb..56c3c72ad8 100644 --- a/api-report/common.txt +++ b/api-report/common.txt @@ -179,6 +179,7 @@ export "./internal/governance-policy" (./src/governance-policy.ts) type ApifyLimits BUILTIN_GOVERNANCE_POLICY type EffectiveGovernancePolicy + GITHUB_WRITE_REPOSITORIES_MAX GOVERNANCE_POLICY_MAX_BYTES GOVERNANCE_POLICY_PATH type GovernanceCommandRuleIndices @@ -202,6 +203,7 @@ export "./internal/governance-policy" (./src/governance-policy.ts) TrustedSourcesSchema canonicalTrustHost checkGovernancePolicy + githubWriteAllowance matchTrustRules openGovernancePolicyAnchored parseGovernancePolicy diff --git a/api-report/ui-server.txt b/api-report/ui-server.txt index 93aedf7fd0..f564a18265 100644 --- a/api-report/ui-server.txt +++ b/api-report/ui-server.txt @@ -1284,6 +1284,9 @@ signatures (every public export and the types it is made of) command: string; remotes: string[]; }[]>>>; + github: z.ZodOptional>; + }, z.core.$strict>>; hosts: z.ZodOptional>; }, z.core.$strict>>; profiles: z.ZodOptional; + github: { + repositories: string[]; + }; hosts: string[]; }; profiles: { diff --git a/docs/integration-contract.md b/docs/integration-contract.md index 2295bbe33a..19499295f4 100644 --- a/docs/integration-contract.md +++ b/docs/integration-contract.md @@ -47,13 +47,33 @@ shape changes. See [the package API](integration-contract/package-api.md#start-card-persona-choice-3698). This ships in a minor. +## Host GitHub writes and their repository allow-list (additive, 0.45.0, #3798) + +Both first-party backends register `brain_github_issue_create` and +`brain_github_issue_comment` in every interactive session's fixed roster, +after the two reads, whatever the host's configuration or the turn's +posture; no autonomous roster lists them. A write goes only to a repository +the new governance policy key `outward.github.repositories` lists, exactly as +`owner/repo` or as `owner/*`, compared without case; anything else is +refused with `policy_denied` (`repository_not_allowed`) before any card, and +an absent or empty list refuses every write. Inside the list, the host shows +one per-use card with exactly what will be sent and sends it once on an +unedited approval; a denial, an edited approval or a voice turn +(`approval_declined`) sends nothing. Each decision is an `outward_action` +governance event (`gh_write`) that the turn journal lists as irreversible. +`brain policy check --json` reports `effective.outward.github.repositories` +(default `[]`). Claude's SDK-options roster gains the two names. See +[the MCP component](integration-contract/mcp.md#github-writes-additive-0450-3798) +and [supported inputs](supported-inputs.md#governance-policy). +This ships in a minor. + ## Host GitHub tools (additive, 0.45.0, #3797) Both first-party backends' interactive sessions gain two host-executed read tools in their fixed roster: `brain_github_issue_read` and `brain_github_issue_search` (`mcp__brain-ui__*` on Claude, plain on pi). Two write tools, `brain_github_issue_create` and `brain_github_issue_comment`, are -declared with their schemas and payloads and registered by #3798. Results are +declared with their schemas and payloads, and registered since #3798. Results are typed payloads for an issue, a pull request and a search, with bounded lists carrying `total_count` and `has_more`, untrusted text marked in the schema, and direct links that pass the exported `githubDirectUrl` and diff --git a/docs/integration-contract/cli.md b/docs/integration-contract/cli.md index f53f6f1863..9463ccb0a0 100644 --- a/docs/integration-contract/cli.md +++ b/docs/integration-contract/cli.md @@ -481,6 +481,9 @@ the file enables it. Since #3160 (additive) `apify` also carries `expires_at` normalized to an ISO 8601 UTC instant. Since #3161 (additive) `apify` also carries `limits`, `null` unless the file sets the complete [limits object](../supported-inputs.md#governance-policy). +Since #3798 (additive), `effective.outward` also includes +`github: { repositories: [] }` by default, or the file's validated +`outward.github.repositories` entries in their order and spelling. Since #3607 (additive), `effective.taint` also includes `trusted_sources: []` by default, or the complete validated canonical trust entries from the [supported input](../supported-inputs.md#prospective-trust-policy-data-additive-3607), diff --git a/docs/integration-contract/mcp.md b/docs/integration-contract/mcp.md index 6c4d82cbe4..0106f612fd 100644 --- a/docs/integration-contract/mcp.md +++ b/docs/integration-contract/mcp.md @@ -1365,15 +1365,16 @@ UI bridge: Claude names them `mcp__brain-ui__` and loads them eagerly; pi attaches plain names. They are in every interactive session's fixed roster (typed, voice and no-grant-surface), after `read_attachment`, whether or not the host holds a credential, and auto-allowed. Restricted autonomous rosters -do not include them. The two write tools are declared here and registered, -with their approval cards and repository allow-list, by #3798. +do not include them. Since #3798 (additive) both backends also attach the two +write tools, after the reads, in the same roster and order and under the same +conditions; see [Writes](#github-writes-additive-0450-3798). | Tool | Input | Registered | |---|---|---| | `brain_github_issue_read` | `repository` (`owner/repo`), `number` (integer 1–2147483647) | 0.45.0 (#3797) | | `brain_github_issue_search` | `repository`, `query` (1–256 characters; `repo:`, `org:`, `user:` and `owner:` qualifiers refused), `kind?` (`issue`, `pull_request`, `any`; default `any`), `state?` (`open`, `closed`, `any`; default `any`), `limit?` (1–30, default 10) | 0.45.0 (#3797) | -| `brain_github_issue_create` | `repository`, `title` (1–256), `body?` (up to 65,536), `labels?` (up to 10 names) | #3798 | -| `brain_github_issue_comment` | `repository`, `number`, `body` (1–65,536) | #3798 | +| `brain_github_issue_create` | `repository`, `title` (1–256), `body?` (up to 65,536), `labels?` (up to 10 names) | 0.45.0 (#3798) | +| `brain_github_issue_comment` | `repository`, `number`, `body` (1–65,536) | 0.45.0 (#3798) | `repository` follows GitHub's name grammar: owner `[A-Za-z0-9-]{1,39}`, repository `[A-Za-z0-9._-]{1,100}` and not `.` or `..`. Inputs are strict @@ -1384,7 +1385,9 @@ Each result is one JSON document, `{ ok: true, tool, result }` or `rate_limited`, `upstream_error`, `policy_denied` or `approval_declined`. `unavailable` carries `reason` `no_credential` (the host has no `BRAIN_UI_GITHUB_TOOLS_TOKEN`), `credential_rejected`, `no_host` (no host -handler in this turn) or `not_registered` (a write tool before #3798). +handler in this turn), `recording_unavailable` (a write's approval could not +be recorded) or, before #3798 only, `not_registered`. The write reasons are +listed under [Writes](#github-writes-additive-0450-3798). **Payloads.** `result` is typed data, never formatted text (`GITHUB_RESULT_SCHEMAS`). A read returns `kind: "issue"` or @@ -1449,6 +1452,60 @@ any GitHub text returns, the session's taint is recorded with the new source `github_result` ([governance events](../http-api.md)); if that record cannot be written, the text is withheld. +### GitHub writes (additive, 0.45.0, #3798) + +`brain_github_issue_create` files one issue and `brain_github_issue_comment` +posts one comment, through the same credential and API origin. A write goes +only to a repository the turn's admitted governance policy lists under +[`outward.github.repositories`](../supported-inputs.md#governance-policy). +The host decides each call in this order, and nothing reaches GitHub before +the last step: + +1. **Allow-list.** A repository the list does not open is refused with + `policy_denied`, `reason: "repository_not_allowed"`, and a message naming + `outward.github.repositories`. No card is shown. An absent or empty list, + or a turn under no governance policy, refuses every write. +2. **Posture.** A voice turn is refused with `approval_declined`, + `reason: "voice_posture"`, before any card: voice can refuse a write but + never approve one. A turn with no write surface, such as any autonomous + turn, is refused with `policy_denied`, `reason: "no_write_surface"`. +3. **Credential.** Without `BRAIN_UI_GITHUB_TOOLS_TOKEN`, `unavailable` + (`no_credential`), before any card. +4. **Card.** One per-use command card on the turn's own approval surface, + named with the backend's visible tool name. Its input is exactly what is + sent: `{ repository, title, body?, labels? }` for an issue and + `{ repository, number, body }` for a comment, after the schema's trimming, + with an absent field neither shown nor sent. Its description says the + write is sent once, in the user's name, and cannot be undone, and notes a + session that has read untrusted input. The card is never remembered. +5. **Answer.** A denial is `approval_declined`, `reason: "declined"`. An + approval that comes back with a changed input is `approval_declined`, + `reason: "edited"`, and sends nothing; the model must make the call again, + which runs every step for the new input. A turn that ended or lost its + authority while the card was open sends nothing (`upstream_error`, + `reason: "cancelled"`). +6. **Send.** One `POST` to the fixed API origin, never retried and never + redirected. A failure that GitHub answered says nothing was written; a + timeout or network failure says the write may still have been made. + +Both backends auto-allow the write tools in a typed turn with a grant surface +and a host handler, so the host's card is the only one. In a voice or +no-grant turn the runtime's own permission boundary refuses them before the +host is reached, and the roster is unchanged. + +A success returns `kind: "issue_created"` (`repository`, `number`, `title`, +`labels`, `created_at`, `html_url`) or `kind: "comment_created"` +(`repository`, `number`, `comment_id`, `created_at`, `html_url`); `html_url` +passes `githubDirectUrl` for the created issue or comment, or is null. A +write's own result does not taint the session. + +Each refusal at steps 1, 2 and 5, each answer and each approval is recorded as an `outward_action` governance +event with `action: "gh_write"`, `target` `owner/repo` (an issue) or +`owner/repo#n` (a comment), the card's input, `tainted`, `historyRewrite: +false`, `rule: null` and `decision` `refused`, `declined` or `approved`. The +approval is recorded before the request is sent; if it cannot be recorded, +nothing is sent. The turn journal lists every one as irreversible. + ## Host-owned web tools (additive, 0.45.0, #3685) The pi backend's ordinary governed and strict interactive sessions list four diff --git a/docs/supported-inputs.md b/docs/supported-inputs.md index 6f18e95350..9b90dc5714 100644 --- a/docs/supported-inputs.md +++ b/docs/supported-inputs.md @@ -67,7 +67,7 @@ objects merge per field. No value grants authority to autonomous turns. | `scope` | `max_files_changed`, `max_minutes`, `max_tool_calls`, `max_bytes_written` | Nonnegative safe integers, except finite minutes. Defaults: 1,000 paths, 120 minutes, 500 calls, 4 GiB. `max_files_changed` counts changed paths outside `workspaces/`; `max_bytes_written` counts workspace writes too. Path/byte defaults are provisional approved values, not measured distributions. | | `commands` | `deny`, `confirm`: arrays of `{ pattern: string, reason?: string }` | Additions to existing permissions, default `[]`. Regex sources preserve their literal anchors and compile case-insensitively under [confirmation rules](decisions/confirm-patterns.md). Mixed lists retain valid entries in order and report skipped sources; nonempty entirely invalid lists refuse. | | `egress` | `mode`: `record`/`allowlist`; `allow`, `deny`: string arrays; `max_bytes_per_turn`: nonnegative safe integer | `record`, empty lists and no byte cap by default. This reader does not establish network enforcement. | -| `outward` | `allow`: array of `{ command: string, remotes: string[] }`; `hosts`: string array | Default empty additions to the existing outward-action rules and built-in destination list. Parsing grants no action. | +| `outward` | `allow`: array of `{ command: string, remotes: string[] }`; `hosts`: string array; `github`: `{ repositories: string[] }` (at most 256) | Default empty additions to the existing outward-action rules and built-in destination list. Parsing grants no action. `github.repositories` (additive, #3798) lists the repositories the host GitHub write tools may write to: each entry is `owner/repo` exactly or `owner/*` for every repository of one owner, with GitHub's name grammar (owner `[A-Za-z0-9-]{1,39}`, repository `[A-Za-z0-9._-]{1,100}`, not `.` or `..`). Owner and repository compare without case. No other pattern exists, and one malformed entry, or an unknown key in `github`, makes the policy invalid rather than being skipped. Absent or empty, the default, no GitHub write is admitted. A listed repository still needs a per-use approval card for each write; see [the MCP contract](integration-contract/mcp.md#github-writes-additive-0450-3798). | | `taint` | `egress: { allow: string[] }`, `trusted_sources: TrustRule[]` | Both lists default to `[]`; trust data and pure candidate matching are described below (#3607). No runtime trust capability is enabled. Default empty egress additions; session-derived hosts/inference relay and taint enforcement remain their owning guardrail's responsibility. Validated provider-relay requests are outside taint narrowing and create no taint ([#3246](integration-contract.md#provider-relay-requests-and-session-taint-breaking-before-10-3246)); this list never needs a provider host for them. | | `providers` | Array of `{ paths?: string[], types?: string[], allow: string[] }` | Default `[]`. At least one selector is present. Paths use canonical brain-relative Bun glob patterns; types are exact runtime taxonomy names. Either selector matches; every matching rule must allow the actual recipient. Unknown recipients cannot authorize matching content. | | `apify` | `enabled`: boolean; `discovery`, `actors`: `deny`, `ask` or `allow`; `actor_grants`: array of `{ account_id, actor_id, build_number, profile_id, schema_sha256, pricing_sha256, origins, expires_at, max_run_usd }` (at most 64); `limits`: `{ run_usd, turn_usd, session_usd, day_usd, max_runs_per_turn, max_requests_per_turn, max_concurrent_runs, max_runtime_seconds, max_result_items, max_result_bytes, max_retention_seconds }` | Default `{ enabled: false, discovery: ask, actors: ask, actor_grants: [], limits: null }` (additive, #3159, #3160 and #3161). Only `enabled: true` lets the server use its host-only `APIFY_TOKEN`; until then it contacts no Apify endpoint, whatever credential exists. An invalid policy file disables Apify rather than keeping an earlier enablement. `discovery` governs catalog searches and Actor inspection, which send the query or the chosen Actor's identifier to Apify; it never permits a run. `actors: deny` refuses every run; both `ask` and `allow` require an Actor's first approval. Approve once authorizes one prepared invocation; approve always persists approval by brain, principal, account and immutable Actor id across sessions, inputs and builds. Historical `actor_grants` entries remain parseable and revocable but do not become Actor-wide approvals. Their legacy fields and expiry syntax are unchanged. `limits` is the only spending entitlement: without it no run is admitted. With it, every field is required. Amounts are USD from 0 to 1,000,000. Counts are whole numbers up to 1,000,000. `max_runtime_seconds` is at most 7 days, `max_result_items` at most 1,000,000, `max_result_bytes` at most 1 GiB and `max_retention_seconds` at most 30 days. Legacy `max_result_items` and `max_result_bytes` remain parseable but do not truncate Actor content (#3580). Zero refuses the remaining allowances. `run_usd` bounds a run's whole reservation: its cap plus its reserved lifecycle requests and remote storage. `turn_usd`, `session_usd` and `day_usd` count pending reservations as spent and apply alongside, never above, `budgets`. `day_usd` and `max_concurrent_runs` are account-wide across brains. `max_requests_per_turn` counts every Apify request in a turn. Results stay readable for `max_retention_seconds` after a run ends, which never shortens Apify's own storage retention. See the [current Apify decision](decisions/apify-actor-approval.md). | diff --git a/packages/common/src/governance-policy.ts b/packages/common/src/governance-policy.ts index efde324fc2..e7d03820ea 100644 --- a/packages/common/src/governance-policy.ts +++ b/packages/common/src/governance-policy.ts @@ -34,6 +34,37 @@ const outwardRules = z.array(z.strictObject({ command: text, remotes: strings }) return valid; }); +/** GitHub's owner and repository name grammar, as the host GitHub tools check it (#3797). */ +const GITHUB_OWNER = "[A-Za-z0-9-]{1,39}"; +const GITHUB_REPO = "[A-Za-z0-9._-]{1,100}"; +const GITHUB_WRITE_ENTRY = new RegExp(`^${GITHUB_OWNER}/(?:\\*|${GITHUB_REPO})$`, "u"); +/** The most entries one `outward.github.repositories` list may hold. */ +export const GITHUB_WRITE_REPOSITORIES_MAX = 256; +/** + * The repositories open to the host GitHub write tools (#3798): `owner/repo` + * exactly, or every repository of one owner as `owner/*`. Nothing else is a + * pattern, and a malformed entry invalidates the policy rather than being + * skipped, so a typo never widens or silently narrows the list. + */ +const githubWriteRepositories = z.array(z.string().regex(GITHUB_WRITE_ENTRY, "Use owner/repo or owner/* with GitHub's name rules") + .refine(entry => !/\/\.{1,2}$/u.test(entry), "A repository cannot be named . or ..")).max(GITHUB_WRITE_REPOSITORIES_MAX); + +/** + * The first `outward.github.repositories` entry that opens `repository` + * (`owner/repo`) to GitHub writes, with its index, or null. Owner and + * repository compare without case, as GitHub's names do. An absent or empty + * list opens nothing. + */ +export function githubWriteAllowance(repositories: readonly string[], repository: string): { index: number; entry: string } | null { + const [owner, repo, ...rest] = repository.toLowerCase().split("/"); + if (!owner || !repo || repo === "*" || rest.length) return null; + for (const [index, entry] of repositories.entries()) { + const [allowedOwner, allowedRepo] = entry.toLowerCase().split("/"); + if (allowedOwner === owner && (allowedRepo === "*" || allowedRepo === repo)) return { index, entry }; + } + return null; +} + /** Each Apify consent family independently refuses, asks per operation, or admits what policy names (#3160). */ const apifyMode = z.enum(["deny", "ask", "allow"]); export const APIFY_MAX_ACTOR_GRANTS = 64; @@ -107,7 +138,9 @@ export const GovernancePolicySchema = z.strictObject({ scope: z.strictObject({ max_files_changed: count.optional(), max_minutes: amount.optional(), max_tool_calls: count.optional(), max_bytes_written: count.optional() }).optional(), commands: z.strictObject({ deny: commands.optional(), confirm: commands.optional() }).optional(), egress: z.strictObject({ mode: z.enum(["record", "allowlist"]).optional(), allow: strings.optional(), deny: strings.optional(), max_bytes_per_turn: count.optional() }).optional(), - outward: z.strictObject({ allow: outwardRules.optional(), hosts: strings.optional() }).optional(), + outward: z.strictObject({ allow: outwardRules.optional(), hosts: strings.optional(), + /** Additive (#3798): the repositories the host GitHub write tools may write to; absent or empty, none. */ + github: z.strictObject({ repositories: githubWriteRepositories.optional() }).optional() }).optional(), taint: z.strictObject({ egress: z.strictObject({ allow: strings }).optional(), trusted_sources: TrustedSourcesSchema.optional() }).optional(), providers: z.array(z.strictObject({ paths: z.array(relativePath).optional(), types: strings.optional(), allow: strings }) .refine(rule => rule.paths !== undefined || rule.types !== undefined, "A provider rule needs paths or types") @@ -143,7 +176,7 @@ export const BUILTIN_GOVERNANCE_POLICY = { scope: { max_files_changed: 1_000, max_minutes: 120, max_tool_calls: 500, max_bytes_written: 4 * 1024 ** 3 }, commands: { deny: [] as Array<{ pattern: string; reason?: string }>, confirm: [] as Array<{ pattern: string; reason?: string }> }, egress: { mode: "record" as "record" | "allowlist", allow: [] as string[], deny: [] as string[] }, - outward: { allow: [] as Array<{ command: string; remotes: string[] }>, hosts: [] as string[] }, + outward: { allow: [] as Array<{ command: string; remotes: string[] }>, hosts: [] as string[], github: { repositories: [] as string[] } }, taint: { egress: { allow: [] as string[] }, trusted_sources: [] as TrustRule[] }, providers: [] as Array<{ paths: string[]; types?: string[]; allow: string[] }>, apify: { enabled: false as boolean, discovery: "ask" as "deny" | "ask" | "allow", actors: "ask" as "deny" | "ask" | "allow", actor_grants: [] as Array>, limits: null as ApifyLimits | null }, @@ -156,7 +189,7 @@ export function resolveGovernancePolicy(policy: GovernancePolicyInput) { profiles: { ...defaults.profiles, ...policy.profiles }, budgets: { turn: { ...defaults.budgets.turn, ...policy.budgets?.turn }, session: { ...defaults.budgets.session, ...policy.budgets?.session }, day: { ...defaults.budgets.day, ...policy.budgets?.day } }, scope: { ...defaults.scope, ...policy.scope }, commands: { ...defaults.commands, ...policy.commands }, - egress: { ...defaults.egress, ...policy.egress }, outward: { ...defaults.outward, ...policy.outward }, + egress: { ...defaults.egress, ...policy.egress }, outward: { ...defaults.outward, ...policy.outward, github: { ...defaults.outward.github, ...policy.outward?.github } }, taint: { egress: { ...defaults.taint.egress, ...policy.taint?.egress }, trusted_sources: TrustedSourcesSchema.parse(policy.taint?.trusted_sources ?? defaults.taint.trusted_sources) }, // Callers pass parsed output, whose grant instants are already ISO strings. apify: { ...defaults.apify, ...(policy.apify as Partial | undefined) }, diff --git a/packages/core/tests/governance-policy.test.ts b/packages/core/tests/governance-policy.test.ts index f4309aa400..616bb04a72 100644 --- a/packages/core/tests/governance-policy.test.ts +++ b/packages/core/tests/governance-policy.test.ts @@ -1,5 +1,5 @@ import { expect, test } from "bun:test"; -import { parseGovernancePolicy, providerAllows } from "../src/lib/governance-policy"; +import { githubWriteAllowance, parseGovernancePolicy, providerAllows } from "../src/lib/governance-policy"; const parse = (yaml: string, body = "Odysseus keeps policy prose separate.\n") => parseGovernancePolicy(Buffer.from(`---\nschema_version: 1\n${yaml}\n---\n${body}`)); @@ -127,3 +127,35 @@ test("Apify limits are the only spending entitlement: absent grants nothing, pre } expect(parse(limitsYaml({ ...LIMITS, account_usd: 5 })).ok, "APIFY_LIMIT_NO_EXTRA_FIELDS").toBe(false); }); + +test("outward.github.repositories opens nothing by default and admits only exact owner/repo or owner/* entries (#3798)", () => { + expect(parse("profiles: { interactive: governed }").effective.outward, "GITHUB_WRITES_DEFAULT_NONE").toEqual({ allow: [], hosts: [], github: { repositories: [] } }); + expect(parse("outward: { hosts: [api.github.com] }").effective.outward.github, "GITHUB_WRITES_SIBLING_DEFAULT").toEqual({ repositories: [] }); + expect(parse("outward: { github: {} }").effective.outward.github).toEqual({ repositories: [] }); + const listed = parse('outward: { github: { repositories: ["odysseus/ithaca", "odysseus/*", "Circe/aiaia.island", "argo-crew/the_ship-1"] } }'); + expect(listed.ok, listed.errors.join(" ")).toBe(true); + expect(listed.effective.outward.github.repositories).toEqual(["odysseus/ithaca", "odysseus/*", "Circe/aiaia.island", "argo-crew/the_ship-1"]); + for (const entry of ["odysseus", "odysseus/", "/ithaca", "*/*", "*/ithaca", "odysseus/ith*", "odysseus/*/issues", "odysseus/ithaca/", "odysseus/..", "odysseus/.", + "https://github.com/odysseus/ithaca", "github.com/odysseus/ithaca", "odys seus/ithaca", "odysseus_/ithaca", "", `${"o".repeat(40)}/ithaca`, `odysseus/${"i".repeat(101)}`]) { + const parsed = parse(`outward: { github: { repositories: [${JSON.stringify(entry)}] } }`); + expect(parsed.ok, `GITHUB_WRITES_MALFORMED_REFUSED: ${entry}`).toBe(false); + expect(parsed.effective.outward.github, `GITHUB_WRITES_INVALID_OPENS_NOTHING: ${entry}`).toEqual({ repositories: [] }); + } + // A malformed entry beside valid ones refuses the policy: it is never skipped. + expect(parse('outward: { github: { repositories: ["odysseus/ithaca", "odysseus"] } }').ok, "GITHUB_WRITES_MIXED_REFUSED").toBe(false); + for (const yaml of ["outward: { github: { repositories: [odysseus/ithaca], issues: true } }", "outward: { github: { repos: [odysseus/ithaca] } }", + "outward: { github: [odysseus/ithaca] }", "outward: { github: { repositories: odysseus/ithaca } }", "outward: { github: { repositories: [7] } }"]) { + expect(parse(yaml).ok, `GITHUB_WRITES_STRICT: ${yaml}`).toBe(false); + } + expect(parse(`outward: { github: { repositories: ${JSON.stringify(Array.from({ length: 257 }, (_, index) => `odysseus/ship-${index}`))} } }`).ok, "GITHUB_WRITES_BOUNDED").toBe(false); +}); + +test("githubWriteAllowance matches exactly or by owner wildcard, without case, and nothing else", () => { + const list = ["odysseus/ithaca", "Circe/*"]; + expect(githubWriteAllowance(list, "odysseus/ithaca")).toEqual({ index: 0, entry: "odysseus/ithaca" }); + expect(githubWriteAllowance(list, "ODYSSEUS/Ithaca")).toEqual({ index: 0, entry: "odysseus/ithaca" }); + expect(githubWriteAllowance(list, "circe/aiaia")).toEqual({ index: 1, entry: "Circe/*" }); + for (const repository of ["odysseus/argo", "odysseus/ithaca-archive", "odysseu/ithaca", "circe", "circe/*", "circe/aiaia/x", ""]) + expect(githubWriteAllowance(list, repository), `GITHUB_WRITES_NOT_ALLOWED: ${repository}`).toBeNull(); + expect(githubWriteAllowance([], "odysseus/ithaca"), "GITHUB_WRITES_EMPTY_LIST").toBeNull(); +}); diff --git a/packages/ui-backend-claude/src/github-tools.ts b/packages/ui-backend-claude/src/github-tools.ts index b218935471..bed22281ba 100644 --- a/packages/ui-backend-claude/src/github-tools.ts +++ b/packages/ui-backend-claude/src/github-tools.ts @@ -1,17 +1,20 @@ import type { z } from "zod"; import type { createSdkMcpServer } from "@anthropic-ai/claude-agent-sdk"; -import { GITHUB_READ_TOOL_CONTRACTS, handleGithubTool, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; +import { GITHUB_TOOL_CONTRACTS, handleGithubTool, type BackendBridge } from "@schlessera/brain-ui-sdk/server"; /** - * The host GitHub read tools (#3797), forwarded to the host, which binds the - * turn and holds the dedicated credential. Registered as full strict objects - * (the SDK's raw-shape helper strips extra keys). A missing host handler or - * credential is an executable refusal, never a schema removal, so the roster - * stays fixed whatever the host's configuration. + * The host GitHub tools, reads (#3797) and writes (#3798), forwarded to the + * host, which binds the turn, holds the dedicated credential, checks a + * write's repository against the policy allow-list and shows its approval + * card. Registered as full strict objects (the SDK's raw-shape helper strips + * extra keys), all four in the contract's fixed order. A missing host + * handler, credential, policy entry or grant surface is an executable + * refusal, never a schema removal, so the roster stays fixed whatever the + * host's configuration or the turn's posture. */ export function registerGithubTools(server: ReturnType["instance"], bridge: Pick, observe?: (name: string, description: string, schema: z.ZodObject) => void) { - for (const contract of GITHUB_READ_TOOL_CONTRACTS) { + for (const contract of GITHUB_TOOL_CONTRACTS) { // One definition feeds both the observed roster and the registration. const definition = { description: contract.description, inputSchema: contract.input, _meta: { "anthropic/alwaysLoad": true } }; observe?.(contract.name, definition.description, definition.inputSchema); @@ -20,7 +23,7 @@ export function registerGithubTools(server: ReturnType visibleToolName(name, "claude"))); + // GitHub writes (#3798): the host checks the policy allow-list and asks + // per exact write on its own card; a runtime card would ask twice and + // offer a rememberable grant. Voice and no-grant turns keep the runtime + // gate, which refuses them before the host is reached. + if (req.bridge.github && !req.noGrantSurface && req.posture !== "voice") + allowed.push(visibleToolName(GITHUB_TOOL_NAMES.create, "claude"), visibleToolName(GITHUB_TOOL_NAMES.comment, "claude")); // No side effect and no host handler: the block is part of the answer, and // an approval card for drawing a table would be the surface asking // permission to answer. diff --git a/packages/ui-backend-claude/src/tool-availability.ts b/packages/ui-backend-claude/src/tool-availability.ts index b5fa75503c..0332d4215e 100644 --- a/packages/ui-backend-claude/src/tool-availability.ts +++ b/packages/ui-backend-claude/src/tool-availability.ts @@ -1,4 +1,4 @@ -import { APIFY_TOOL_NAMES, GITHUB_READ_TOOL_NAMES, type StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { APIFY_TOOL_NAMES, GITHUB_TOOL_NAMES, GITHUB_TOOL_NAME_LIST, type StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; const handlers: Record = { ask_user: "askUser", ask_user_list: "askUserList", ask_user_rank: "askUserRank", @@ -11,13 +11,14 @@ const handlers: Record = { brain_compute_status: "compute", brain_compute_cancel: "compute", brain_compute_collect: "compute", ...Object.fromEntries(Object.values(APIFY_TOOL_NAMES).map(name => [name, "apify"])), read_attachment: "readAttachment", - ...Object.fromEntries(GITHUB_READ_TOOL_NAMES.map(name => [name, "github"])), + ...Object.fromEntries(GITHUB_TOOL_NAME_LIST.map(name => [name, "github"])), brain_add: "applyBrain", brain_update: "applyBrain", brain_archive: "applyBrain", write_file: "applyBrain", edit_file: "applyBrain", apply_staged_changes: "applyBrain", }; const visual = new Set(["request_image_mask", "ask_user_list", "ask_user_rank", "ask_user_form"]); -// Apify stays inside interactive typed turns (#3162): voice and no-grant turns keep their memberships. -const interactive = new Set(["propose_policy_change", "inbox_add", "resolve_action", "complete_share", ...Object.values(APIFY_TOOL_NAMES)]); +// Apify (#3162) and GitHub writes (#3798) stay inside interactive typed turns: voice and no-grant turns keep their memberships. +const interactive = new Set(["propose_policy_change", "inbox_add", "resolve_action", "complete_share", ...Object.values(APIFY_TOOL_NAMES), + GITHUB_TOOL_NAMES.create, GITHUB_TOOL_NAMES.comment]); /** Registration is stable; these live facts are authority only at call time. */ export function toolAvailabilityRefusal(req: StartTurnRequest, toolName: string): string | undefined { diff --git a/packages/ui-backend-claude/tests/fixtures/sdk-options-snapshot.json b/packages/ui-backend-claude/tests/fixtures/sdk-options-snapshot.json index 0030cbca5a..ce85e12fab 100644 --- a/packages/ui-backend-claude/tests/fixtures/sdk-options-snapshot.json +++ b/packages/ui-backend-claude/tests/fixtures/sdk-options-snapshot.json @@ -95,6 +95,8 @@ "brain_apify_revoke", "brain_github_issue_read", "brain_github_issue_search", + "brain_github_issue_create", + "brain_github_issue_comment", "read_attachment", "write_file", "edit_file", @@ -104,7 +106,7 @@ "brain_archive", "brain_read_base" ], - "toolSchemasSha256": "e670ae8927b85bc0127216096790b15cf924c9057e2ac5043a21877bcd819e77", + "toolSchemasSha256": "8e6d30b6472a6003930e4411a2f6466ed1db23552ee35eaa4b3db52d5b104fda", "mcpServers": [ "brain-ui" ], @@ -293,6 +295,8 @@ "brain_apify_revoke", "brain_github_issue_read", "brain_github_issue_search", + "brain_github_issue_create", + "brain_github_issue_comment", "read_attachment", "write_file", "edit_file", @@ -302,7 +306,7 @@ "brain_archive", "brain_read_base" ], - "toolSchemasSha256": "e670ae8927b85bc0127216096790b15cf924c9057e2ac5043a21877bcd819e77", + "toolSchemasSha256": "8e6d30b6472a6003930e4411a2f6466ed1db23552ee35eaa4b3db52d5b104fda", "mcpServers": [ "brain-ui" ], @@ -478,6 +482,8 @@ "brain_apify_revoke", "brain_github_issue_read", "brain_github_issue_search", + "brain_github_issue_create", + "brain_github_issue_comment", "read_attachment", "write_file", "edit_file", @@ -487,7 +493,7 @@ "brain_archive", "brain_read_base" ], - "toolSchemasSha256": "e670ae8927b85bc0127216096790b15cf924c9057e2ac5043a21877bcd819e77", + "toolSchemasSha256": "8e6d30b6472a6003930e4411a2f6466ed1db23552ee35eaa4b3db52d5b104fda", "mcpServers": [ "brain-ui" ], @@ -685,6 +691,8 @@ "brain_apify_revoke", "brain_github_issue_read", "brain_github_issue_search", + "brain_github_issue_create", + "brain_github_issue_comment", "read_attachment", "write_file", "edit_file", @@ -694,7 +702,7 @@ "brain_archive", "brain_read_base" ], - "toolSchemasSha256": "e670ae8927b85bc0127216096790b15cf924c9057e2ac5043a21877bcd819e77", + "toolSchemasSha256": "8e6d30b6472a6003930e4411a2f6466ed1db23552ee35eaa4b3db52d5b104fda", "mcpServers": [ "brain-ui" ], diff --git a/packages/ui-backend-claude/tests/github-write-availability.test.ts b/packages/ui-backend-claude/tests/github-write-availability.test.ts new file mode 100644 index 0000000000..319132319b --- /dev/null +++ b/packages/ui-backend-claude/tests/github-write-availability.test.ts @@ -0,0 +1,24 @@ +/** + * The Claude permission boundary for the host GitHub write tools (#3798): + * the roster is fixed, so a voice or no-grant turn still lists them, and + * this boundary refuses them there before the host is reached; a typed turn + * with a host handler admits them, and the host asks on its own card. + */ +import { expect, test } from "bun:test"; +import type { StartTurnRequest } from "@schlessera/brain-ui-sdk/server"; +import { toolAvailabilityRefusal } from "../src/tool-availability.js"; + +const github = async () => ({ ok: false as const, tool: "brain_github_issue_create" as const, error: { code: "unavailable" as const, reason: "no_credential", message: "none" } }); +const request = (extra: Partial, handler = true) => + ({ prompt: "File the suitors issue", bridge: { emit() {}, requestPermission: async () => ({ behavior: "allow" }), ...(handler ? { github } : {}) }, ...extra }) as unknown as StartTurnRequest; + +test("a write tool is admitted only in a typed turn with a grant surface and a host handler", () => { + for (const name of ["brain_github_issue_create", "brain_github_issue_comment"]) for (const visible of [name, `mcp__brain-ui__${name}`]) { + expect(toolAvailabilityRefusal(request({}), visible), `CLAUDE_GITHUB_WRITE_TYPED ${visible}`).toBeUndefined(); + expect(toolAvailabilityRefusal(request({ posture: "voice" }), visible), `CLAUDE_GITHUB_WRITE_VOICE ${visible}`).toContain("interactive typed grant surface"); + expect(toolAvailabilityRefusal(request({ noGrantSurface: true }), visible), `CLAUDE_GITHUB_WRITE_NO_GRANT ${visible}`).toContain("interactive typed grant surface"); + expect(toolAvailabilityRefusal(request({}, false), visible), `CLAUDE_GITHUB_WRITE_NO_HANDLER ${visible}`).toContain("no available host handler"); + } + // Reads keep their membership in voice and no-grant turns. + expect(toolAvailabilityRefusal(request({ posture: "voice" }), "mcp__brain-ui__brain_github_issue_read")).toBeUndefined(); +}); diff --git a/packages/ui-backend-claude/tests/sdk-options-mcp.test.ts b/packages/ui-backend-claude/tests/sdk-options-mcp.test.ts index 979720fa15..712dcc4c4a 100644 --- a/packages/ui-backend-claude/tests/sdk-options-mcp.test.ts +++ b/packages/ui-backend-claude/tests/sdk-options-mcp.test.ts @@ -4,7 +4,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import * as worker from "@schlessera/brain-ui-sdk/internal"; -import { APIFY_TOOL_NAMES, BRAIN_APPLICATION_TOOLS, BRIDGE_TOOL_POSTURE, GITHUB_READ_TOOL_CONTRACTS, GITHUB_READ_TOOL_NAMES, READ_ATTACHMENT_TOOL_NAME, toolInputJsonSchema } from "@schlessera/brain-ui-sdk/server"; +import { APIFY_TOOL_NAMES, BRAIN_APPLICATION_TOOLS, BRIDGE_TOOL_POSTURE, GITHUB_READ_TOOL_NAMES, GITHUB_TOOL_CONTRACTS, GITHUB_TOOL_NAME_LIST, GITHUB_TOOL_NAMES, READ_ATTACHMENT_TOOL_NAME, toolInputJsonSchema } from "@schlessera/brain-ui-sdk/server"; import { createClaudeSdkTurn } from "../src/sdk-options.js"; @@ -76,7 +76,7 @@ describe("the SDK options a turn is built with", () => { // The full roster, because a handler that silently failed to register // would leave a tool deferred by absence rather than by policy. expect(tools.map((tool) => tool.name).sort()).toEqual( - [...BRIDGE_TOOL_POSTURE.names, "propose_policy_change", "brain_read_base", ...Object.values(BRAIN_APPLICATION_TOOLS), ...Object.values(APIFY_TOOL_NAMES), READ_ATTACHMENT_TOOL_NAME, ...GITHUB_READ_TOOL_NAMES].sort() + [...BRIDGE_TOOL_POSTURE.names, "propose_policy_change", "brain_read_base", ...Object.values(BRAIN_APPLICATION_TOOLS), ...Object.values(APIFY_TOOL_NAMES), READ_ATTACHMENT_TOOL_NAME, ...GITHUB_TOOL_NAME_LIST].sort() ); for (const tool of tools) { expect(tool._meta?.["anthropic/alwaysLoad"]).toBe(true); @@ -107,9 +107,13 @@ describe("the SDK options a turn is built with", () => { } finally { await finish?.(); rmSync(brain, { recursive: true, force: true }); } }); - // #3797: the GitHub read tools are in every interactive mode's roster, with or - // without a host handler, with the contract's exact schemas; never in an autonomous roster. - for (const mode of ["typed", "no-grant", "voice", "autonomous"] as const) for (const handler of [true, false]) test(`GitHub read tools: ${mode} ${handler ? "with" : "without"} a host handler`, async () => { + // #3797, #3798: all four GitHub tools, reads and writes, are in every + // interactive mode's roster in the contract's order, with or without a host + // handler, with the contract's exact schemas; never in an autonomous roster. + // Reads are auto-allowed wherever a handler exists; writes only in a typed + // turn with a grant surface, where the host asks on its own card. + const githubRosters = new Map(); + for (const mode of ["typed", "no-grant", "voice", "autonomous"] as const) for (const handler of [true, false]) test(`GitHub tools: ${mode} ${handler ? "with" : "without"} a host handler`, async () => { const brain = mkdtempSync(join(tmpdir(), "github-roster-")); let finish: (() => Promise) | undefined; try { @@ -127,8 +131,12 @@ describe("the SDK options a turn is built with", () => { const github = tools.filter(tool => tool.name.startsWith("brain_github_")); if (mode === "autonomous") expect(github, "GITHUB_ABSENT_FROM_AUTONOMOUS_ROSTER").toEqual([]); else { - expect(github.map(tool => tool.name), `GITHUB_STABLE_ROSTER_${mode}`).toEqual([...GITHUB_READ_TOOL_NAMES]); - for (const contract of GITHUB_READ_TOOL_CONTRACTS) { + expect(github.map(tool => tool.name), `GITHUB_STABLE_ROSTER_${mode}`).toEqual([...GITHUB_TOOL_NAME_LIST]); + // Byte-identical definitions in every interactive mode: posture, profile and handler never change them. + const definitions = JSON.stringify(github.map(tool => [tool.name, tool.description, tool.inputSchema])); + for (const previous of githubRosters.values()) expect(definitions, `GITHUB_ROSTER_IDENTICAL_${mode}`).toBe(previous as string); + githubRosters.set(`${mode}:${handler}`, definitions); + for (const contract of GITHUB_TOOL_CONTRACTS) { const listed = github.find(tool => tool.name === contract.name)!; expect(listed.description).toBe(contract.description); const { $schema: _schema, ...schema } = listed.inputSchema as Record; @@ -137,6 +145,8 @@ describe("the SDK options a turn is built with", () => { } const allowed = GITHUB_READ_TOOL_NAMES.map(name => `mcp__brain-ui__${name}`); for (const name of allowed) expect(turn.options.allowedTools?.includes(name) ?? false, `GITHUB_AUTO_ALLOWED_${mode}`).toBe(handler && mode !== "autonomous"); + for (const name of [GITHUB_TOOL_NAMES.create, GITHUB_TOOL_NAMES.comment].map(name => `mcp__brain-ui__${name}`)) + expect(turn.options.allowedTools?.includes(name) ?? false, `GITHUB_WRITE_AUTO_ALLOWED_${mode}`).toBe(handler && mode === "typed"); await client.close(); } finally { await finish?.(); rmSync(brain, { recursive: true, force: true }); } }); diff --git a/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts b/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts index a9b2ba7c05..e112cab6d4 100644 --- a/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts +++ b/packages/ui-backend-claude/tests/sdk-options-snapshot.test.ts @@ -24,6 +24,8 @@ import { SNAPSHOT_MODES, sdkOptionsSnapshot } from "./helpers/sdk-options-snapsh * #3797 adds the two host GitHub read tools to the four interactive modes' * stable roster (names and the schema digest); allowlists, prompts and * autonomous modes stay byte-identical. + * #3798 adds the two host GitHub write tools after them, in the same four + * modes (names and the schema digest); everything else stays byte-identical. * Regenerate it only for a reviewed, intended change to * the roster, allowlist or system prompt, and say so in the PR. */ diff --git a/packages/ui-backend-pi/src/bridge-tools.ts b/packages/ui-backend-pi/src/bridge-tools.ts index 1177045b8b..256be7e64c 100644 --- a/packages/ui-backend-pi/src/bridge-tools.ts +++ b/packages/ui-backend-pi/src/bridge-tools.ts @@ -1,5 +1,5 @@ import { PROPOSE_POLICY_CHANGE_CONTRACT, PROPOSE_POLICY_CHANGE_INPUT_SCHEMA } from "@schlessera/brain-ui-sdk/tool-contracts"; -import { APIFY_TOOL_CONTRACTS, COMPUTE_TOOL_CONTRACTS, GITHUB_READ_TOOL_CONTRACTS, handleGithubTool, INBOX_TOOL_CONTRACTS, READ_ATTACHMENT_CONTRACT, REFERENCE_TOOL_CONTRACTS, WEB_TOOL_CONTRACTS, handleApifyTool, handleComputeTool, handleInboxTool, handleReadAttachment, handleReferenceTool, handleWebTool } from "@schlessera/brain-ui-sdk/server"; +import { APIFY_TOOL_CONTRACTS, COMPUTE_TOOL_CONTRACTS, GITHUB_TOOL_CONTRACTS, handleGithubTool, INBOX_TOOL_CONTRACTS, READ_ATTACHMENT_CONTRACT, REFERENCE_TOOL_CONTRACTS, WEB_TOOL_CONTRACTS, handleApifyTool, handleComputeTool, handleInboxTool, handleReadAttachment, handleReferenceTool, handleWebTool } from "@schlessera/brain-ui-sdk/server"; import type { ToolDefinition } from "@earendil-works/pi-coding-agent"; import { ASK_USER_DESCRIPTION, @@ -382,9 +382,11 @@ export function createPiBridgeTools(options: PiBridgeToolOptions): ToolDefinitio return textResult(result.text); }, }); - // GitHub reads (#3797) run on the host, which binds the turn and holds the - // dedicated credential; a refusal, `unavailable` included, is a tool error. - if (capabilities?.github) for (const contract of GITHUB_READ_TOOL_CONTRACTS) tools.push({ + // GitHub reads (#3797) and writes (#3798) run on the host, which binds the + // turn, holds the dedicated credential, checks a write against the policy + // allow-list and asks for it on its own card; a refusal, `unavailable` + // included, is a tool error. All four, in the contract's fixed order. + if (capabilities?.github) for (const contract of GITHUB_TOOL_CONTRACTS) tools.push({ name: contract.name, label: contract.name, description: contract.description, parameters: toPiParameters(contract), async execute(_id: string, input: unknown) { const result = await handleGithubTool(contract.name, input, turn.bridge ?? {}); diff --git a/packages/ui-backend-pi/src/permission-gate.ts b/packages/ui-backend-pi/src/permission-gate.ts index 0128793d44..8578324c7d 100644 --- a/packages/ui-backend-pi/src/permission-gate.ts +++ b/packages/ui-backend-pi/src/permission-gate.ts @@ -36,7 +36,8 @@ import type { InlineExtension, ToolCallEvent, ToolCallEventResult } from "@earendil-works/pi-coding-agent"; import { APIFY_TOOL_NAMES, - GITHUB_READ_TOOL_NAMES, + GITHUB_TOOL_NAMES, + GITHUB_TOOL_NAME_LIST, WEB_TOOL_NAME_LIST, checkEditedApproval, createToolPermissionRequest, @@ -63,8 +64,9 @@ export interface PermissionGateOptions { export function piToolAvailabilityRefusal(turn: TurnContext, name: string): string | undefined { if (turn.autonomous) return undefined; const visual = ["ask_user_list", "ask_user_rank", "ask_user_form", "request_image_mask"]; - // Apify stays inside interactive typed turns (#3162): voice and no-grant turns keep their memberships. - const interactive = ["propose_policy_change", "inbox_add", "resolve_action", "complete_share", ...Object.values(APIFY_TOOL_NAMES)]; + // Apify (#3162) and GitHub writes (#3798) stay inside interactive typed turns: voice and no-grant turns keep their memberships. + const interactive = ["propose_policy_change", "inbox_add", "resolve_action", "complete_share", ...Object.values(APIFY_TOOL_NAMES), + GITHUB_TOOL_NAMES.create, GITHUB_TOOL_NAMES.comment]; if ([...visual, ...interactive].includes(name) && (turn.noGrantSurface || turn.posture === "voice")) return `Tool "${name}" requires an interactive typed grant surface.`; const handlers: Record = { @@ -78,7 +80,7 @@ export function piToolAvailabilityRefusal(turn: TurnContext, name: string): stri ...Object.fromEntries(Object.values(APIFY_TOOL_NAMES).map(name => [name, "apify"])), read_attachment: "readAttachment", ...Object.fromEntries(WEB_TOOL_NAME_LIST.map(name => [name, "webAccess"])), - ...Object.fromEntries(GITHUB_READ_TOOL_NAMES.map(name => [name, "github"])), + ...Object.fromEntries(GITHUB_TOOL_NAME_LIST.map(name => [name, "github"])), }; const handler = handlers[name]; if (handler && typeof (turn.bridge as unknown as Record | null)?.[handler] !== "function") diff --git a/packages/ui-backend-pi/src/tools.ts b/packages/ui-backend-pi/src/tools.ts index f036bb1542..cab5dba976 100644 --- a/packages/ui-backend-pi/src/tools.ts +++ b/packages/ui-backend-pi/src/tools.ts @@ -1,4 +1,4 @@ -import { APIFY_TOOL_NAMES, ASK_USER_TOOL_NAME, BRIDGE_TOOL_POSTURE, GITHUB_READ_TOOL_NAMES, WEB_TOOL_NAME_LIST } from "@schlessera/brain-ui-sdk/server"; +import { APIFY_TOOL_NAMES, ASK_USER_TOOL_NAME, BRIDGE_TOOL_POSTURE, GITHUB_READ_TOOL_NAMES, GITHUB_TOOL_NAMES, WEB_TOOL_NAME_LIST } from "@schlessera/brain-ui-sdk/server"; /** * The curated brain tool surface for the pi backend. * @@ -156,6 +156,8 @@ export const TOOL_RISK: Record = { web_search: "read", fetch_content: "read", get_search_content: "read", source_check: "read", // Host GitHub reads (#3797): the host reads GitHub with its own credential. brain_github_issue_read: "read", brain_github_issue_search: "read", + // Host GitHub writes (#3798): outward, behind the host's allow-list and per-write card. + brain_github_issue_create: "mutate", brain_github_issue_comment: "mutate", // Echoes the block it was given; the surface draws it. Touches nothing. show_block: "read", // Writes a mask PNG next to its image, but the approval is the mask editor @@ -212,6 +214,10 @@ export const DEFAULT_PI_ALLOWED_TOOLS: readonly string[] = [ // Host GitHub reads (#3797): the host binds the turn, holds the credential // and taints the session; a card would ask to read. ...GITHUB_READ_TOOL_NAMES, + // Host GitHub writes (#3798): the host checks the policy allow-list and asks + // per exact write on its own card; a tool card would ask twice and offer a + // rememberable grant. Voice and no-grant turns refuse before the host. + GITHUB_TOOL_NAMES.create, GITHUB_TOOL_NAMES.comment, // pi-subagents (recommended fan-out extension) — parity with Claude's // auto-allowed Agent tool. NOTE: a child agent's own tool calls run inside // pi's child session with that agent's declared tools, NOT through this diff --git a/packages/ui-backend-pi/tests/github-tools.test.ts b/packages/ui-backend-pi/tests/github-tools.test.ts index 56992dc2b8..403e6acb4d 100644 --- a/packages/ui-backend-pi/tests/github-tools.test.ts +++ b/packages/ui-backend-pi/tests/github-tools.test.ts @@ -1,12 +1,13 @@ /** - * The host GitHub read tools in Pi's roster and gate (#3797): every - * interactive session lists both, with the contract's exact schemas, whether - * or not this turn has a host handler; no autonomous session lists them; the - * gate auto-allows them only when the host can run them; a call forwards the - * parsed input only, and a refusal is a tool error. + * The host GitHub tools in Pi's roster and gate (#3797, #3798): every + * interactive session lists all four, reads and writes, with the contract's + * exact schemas and order, whether or not this turn has a host handler; no + * autonomous session lists them; the gate auto-allows them only when the host + * can run them, and writes only in a typed turn with a grant surface; a call + * forwards the parsed input only, and a refusal is a tool error. */ import { expect, test } from "bun:test"; -import { GITHUB_READ_TOOL_CONTRACTS, GITHUB_READ_TOOL_NAMES, toolInputJsonSchema } from "@schlessera/brain-ui-sdk/server"; +import { GITHUB_READ_TOOL_NAMES, GITHUB_TOOL_CONTRACTS, GITHUB_TOOL_NAME_LIST, GITHUB_TOOL_NAMES, toolInputJsonSchema } from "@schlessera/brain-ui-sdk/server"; import { createSessionPool } from "../src/session-pool.js"; import { createPiBridgeTools } from "../src/bridge-tools.js"; import { createTurnContext } from "../src/turn-context.js"; @@ -27,13 +28,18 @@ async function acquiredTools(request: Record, bridgeExtras: Rec return tools; } -test("every interactive session lists both read tools with the contract's schemas, with or without a host handler", async () => { +test("every interactive session lists all four GitHub tools with the contract's schemas, with or without a host handler", async () => { + let first: string | undefined; for (const [label, request, extras] of [ ["typed", {}, { github }], ["missing-handler", {}, {}], ["voice", { posture: "voice" }, {}], ["no-grant", { noGrantSurface: true }, { github }], ] as const) { const tools = (await acquiredTools(request, extras)).filter(tool => tool.name.startsWith("brain_github_")); - expect(tools.map(tool => tool.name), `PI_GITHUB_STABLE_ROSTER_${label}`).toEqual([...GITHUB_READ_TOOL_NAMES]); - for (const contract of GITHUB_READ_TOOL_CONTRACTS) { + expect(tools.map(tool => tool.name), `PI_GITHUB_STABLE_ROSTER_${label}`).toEqual([...GITHUB_TOOL_NAME_LIST]); + // Byte-identical definitions in every interactive mode: posture and handler never change them. + const definitions = JSON.stringify(tools.map(tool => [tool.name, tool.description, tool.parameters])); + first ??= definitions; + expect(definitions, `PI_GITHUB_ROSTER_IDENTICAL_${label}`).toBe(first); + for (const contract of GITHUB_TOOL_CONTRACTS) { const tool = tools.find(tool => tool.name === contract.name)!; expect(tool.description).toBe(contract.description); expect(JSON.parse(JSON.stringify(tool.parameters)), `PI_GITHUB_EXACT_SCHEMA_${label}_${contract.name}`).toEqual(JSON.parse(JSON.stringify(toolInputJsonSchema(contract)))); @@ -43,7 +49,7 @@ test("every interactive session lists both read tools with the contract's schema test("no autonomous session lists a GitHub tool, restricted or not, even with a handler", async () => { for (const containment of ["restricted", undefined]) { - const autonomous = { origin: "autonomous", persistence: "none", allowedTools: [...GITHUB_READ_TOOL_NAMES], systemPromptAppend: "", ...(containment ? { containment } : {}) }; + const autonomous = { origin: "autonomous", persistence: "none", allowedTools: [...GITHUB_TOOL_NAME_LIST], systemPromptAppend: "", ...(containment ? { containment } : {}) }; const names = (await acquiredTools({ autonomous }, { github })).map(tool => tool.name); expect(names.filter(name => name.startsWith("brain_github_")), `PI_GITHUB_AUTONOMOUS_${containment ?? "governed"}`).toEqual([]); } @@ -65,6 +71,24 @@ test("the gate auto-allows a read tool only when the host can run it", async () } }); +test("the gate auto-allows a write tool only in a typed turn with a grant surface and a host handler, and never shows a runtime card", async () => { + for (const name of [GITHUB_TOOL_NAMES.create, GITHUB_TOOL_NAMES.comment]) { + expect(TOOL_RISK[name], `PI_GITHUB_RISK_${name}`).toBe("mutate"); + expect(DEFAULT_PI_ALLOWED_TOOLS, `PI_GITHUB_ALLOWED_${name}`).toContain(name); + for (const [label, posture, noGrantSurface, handler, expected] of [ + ["typed", undefined, false, true, "allow"], ["voice", "voice", false, true, "deny"], ["no-grant", undefined, true, true, "deny"], ["missing-handler", undefined, false, false, "deny"], + ] as const) { + let cards = 0; + const turn = createTurnContext(); + Object.assign(turn, { ...(posture ? { posture } : {}), noGrantSurface }); + turn.bridge = { emit() {}, requestPermission: async () => { cards++; return { behavior: "allow" }; }, ...(handler ? { github } : {}) } as never; + expect(await decidePiToolPermission({ turn, allowedTools: new Set(DEFAULT_PI_ALLOWED_TOOLS), confirmPatterns: [] }, name, {}, "loom"), `PI_GITHUB_WRITE_${label}_${name}`) + .toMatchObject({ behavior: expected }); + expect(cards, `PI_GITHUB_WRITE_NO_RUNTIME_CARD_${label}_${name}`).toBe(0); + } + } +}); + test("a call forwards the parsed input only, and a refusal is a tool error", async () => { const calls: unknown[] = []; const turn = createTurnContext(); diff --git a/packages/ui-backend-pi/tests/stable-roster.test.ts b/packages/ui-backend-pi/tests/stable-roster.test.ts index d4eb7762b2..277395e1b3 100644 --- a/packages/ui-backend-pi/tests/stable-roster.test.ts +++ b/packages/ui-backend-pi/tests/stable-roster.test.ts @@ -18,7 +18,7 @@ test("Pi production session acquisition builds one full roster even voice-first ...(mode === "voice" ? { posture: "voice" } : {}), noGrantSurface: mode !== "typed" }); const tools = createPiBridgeTools({ brainPath: "/tmp/odysseus", turn: entry.turnContext, capabilities: observed!.caps }); rosters.push(JSON.stringify(tools.map(tool => ({ name: tool.name, description: tool.description, parameters: tool.parameters })))); - for (const name of [...names, "brain_compute_run", "brain_compute_collect", "brain_github_issue_read", "brain_github_issue_search"]) expect(tools.map(tool => tool.name), `PI_FULL_ROSTER_${mode}_${name}`).toContain(name); + for (const name of [...names, "brain_compute_run", "brain_compute_collect", "brain_github_issue_read", "brain_github_issue_search", "brain_github_issue_create", "brain_github_issue_comment"]) expect(tools.map(tool => tool.name), `PI_FULL_ROSTER_${mode}_${name}`).toContain(name); pool.finish(entry); } for (const roster of rosters.slice(1)) expect(roster, "PI_FIXED_VOICE_FIRST_ROSTER").toBe(rosters[0]); diff --git a/packages/ui-sdk/src/tool-contracts/github.ts b/packages/ui-sdk/src/tool-contracts/github.ts index eab0105317..8a8d7c6e60 100644 --- a/packages/ui-sdk/src/tool-contracts/github.ts +++ b/packages/ui-sdk/src/tool-contracts/github.ts @@ -36,7 +36,7 @@ export type GithubToolName = (typeof GITHUB_TOOL_NAMES)[keyof typeof GITHUB_TOOL export type GithubReadToolName = typeof GITHUB_TOOL_NAMES.read | typeof GITHUB_TOOL_NAMES.search; export type GithubWriteToolName = typeof GITHUB_TOOL_NAMES.create | typeof GITHUB_TOOL_NAMES.comment; export const GITHUB_TOOL_NAME_LIST: readonly GithubToolName[] = Object.freeze(Object.values(GITHUB_TOOL_NAMES)); -/** The tools registered today; the write tools join them with their approval cards (#3798). */ +/** The read tools (#3797); the write tools (#3798) follow them in the roster, behind the policy allow-list and a per-write card. */ export const GITHUB_READ_TOOL_NAMES: readonly GithubReadToolName[] = Object.freeze([GITHUB_TOOL_NAMES.read, GITHUB_TOOL_NAMES.search]); export const isGithubToolName = (name: string): name is GithubToolName => (GITHUB_TOOL_NAME_LIST as readonly string[]).includes(name); @@ -127,7 +127,7 @@ export const GITHUB_ISSUE_SEARCH_INPUT_SCHEMA = z.strictObject({ .describe(`Results to return; default ${GITHUB_LIMITS.searchDefault}, at most ${GITHUB_LIMITS.searchMax}`), }); -/** Declared now and registered with its approval card in #3798. */ +/** One issue, sent only to an allow-listed repository after a per-use card (#3798). */ export const GITHUB_ISSUE_CREATE_INPUT_SCHEMA = z.strictObject({ repository, title: z.string().trim().min(1).max(GITHUB_LIMITS.writeTitleChars).describe("The issue title"), @@ -136,7 +136,7 @@ export const GITHUB_ISSUE_CREATE_INPUT_SCHEMA = z.strictObject({ .describe("Existing label names to apply"), }); -/** Declared now and registered with its approval card in #3798. */ +/** One comment, sent only to an allow-listed repository after a per-use card (#3798). */ export const GITHUB_ISSUE_COMMENT_INPUT_SCHEMA = z.strictObject({ repository, number: issueNumber, @@ -313,7 +313,7 @@ export const GITHUB_ISSUE_SEARCH_PAYLOAD_SCHEMA = z.strictObject({ fetched_at: timestamp, }); -/** #3798 fills these; the shape is fixed here so the components bind once. */ +/** What a write returns (#3798); the shape is fixed here so the components bind once. */ export const GITHUB_ISSUE_CREATE_PAYLOAD_SCHEMA = z.strictObject({ kind: z.literal("issue_created"), repository: z.string().max(141), @@ -351,8 +351,13 @@ export type GithubIssueCommentPayload = z.infer readonly string[] | null; + readonly posture: "interactive" | "voice"; + /** The turn's own approval surface. */ + readonly requestPermission: (request: PermissionRequest) => Promise; + /** The tool's name as this backend shows it on the card. */ + readonly toolName: (name: GithubWriteToolName) => string; + /** Whether the session has ingested untrusted input; a failing read counts as tainted. */ + readonly tainted: () => boolean; + /** Whether the turn still holds current authority, checked again after the card. */ + readonly isCurrent: () => boolean; + /** Records the decision. A write is sent only after its approval's record settles without error. */ + readonly govern: (event: GithubOutwardAction) => void | Promise; +} + /** The turn a call belongs to, bound by the host, never by the call. */ export interface GithubToolsTurn { readonly turnId: string; readonly principalId: string; readonly sessionId: () => string | null; readonly signal?: AbortSignal; + /** Present only on a turn that may write (#3798); an autonomous turn has none. */ + readonly write?: GithubWriteTurn; } export interface GithubToolsHostOptions { @@ -324,14 +364,142 @@ export function createGithubToolsHost(options: GithubToolsHostOptions): GithubTo const refusal = (tool: GithubToolName, code: GithubErrorCode, reason: string | null, message: string): GithubToolResult => ({ ok: false, tool, error: { code, reason, message } }); + const noCredential = (tool: GithubToolName) => + refusal(tool, "unavailable", "no_credential", "This host has no GitHub credential for its GitHub tools (BRAIN_UI_GITHUB_TOOLS_TOKEN). GITHUB_TOKEN is never used for them."); + + /** + * One POST against the fixed API origin, sent once. A redirect is not + * followed: repeating a write could file it twice. + */ + async function post(token: string, path: string, payload: Json, signal: AbortSignal | undefined): Promise { + const timeout = AbortSignal.timeout(timeoutMs); + let response: Response; + try { + response = await (options.fetch ?? fetch)(new URL(path, GITHUB_API_ORIGIN), { method: "POST", redirect: "manual", + signal: signal ? AbortSignal.any([signal, timeout]) : timeout, body: JSON.stringify(payload), + headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "content-type": "application/json", + "x-github-api-version": "2022-11-28", "user-agent": "brain-ui" } }); + } catch { + // The request may have reached GitHub: say so rather than invite a duplicate. + throw new GithubRefusal("upstream_error", signal?.aborted ? "cancelled" : timeout.aborted ? "timeout" : "network", + "GitHub did not confirm the write. It may still have been made: read the issue before trying again."); + } + if (!response.ok) { + const limited = response.headers.get("x-ratelimit-remaining") === "0" || response.status === 429; + if (limited) throw new GithubRefusal("rate_limited", null, "GitHub's rate limit for the host credential is spent; nothing was written. Try again later."); + if (response.status === 401) throw new GithubRefusal("unavailable", "credential_rejected", "GitHub rejected the host's GitHub tools credential; nothing was written."); + if (response.status === 404 || response.status === 410) throw new GithubRefusal("not_found", null, "GitHub has no such issue or repository, or the host's credential cannot see it; nothing was written."); + if (response.status === 403) throw new GithubRefusal("forbidden", null, "The host's GitHub credential is not permitted to write here; nothing was written."); + if (response.status === 422) throw new GithubRefusal("invalid_input", "github_validation", "GitHub refused the write as invalid; nothing was written."); + throw new GithubRefusal("upstream_error", `http_${response.status}`, `GitHub answered ${response.status}; the write may not have been made.`); + } + try { return await response.json(); } + catch { throw new GithubRefusal("upstream_error", "malformed", "GitHub accepted the write but returned malformed JSON."); } + } + + /** What one write sends: the card shows `card`, and `payload` is the request body, built from the same values. */ + function prepareWrite(call: Extract) { + if (call.tool === GITHUB_TOOL_NAMES.create) { + const input = GITHUB_ISSUE_CREATE_INPUT_SCHEMA.parse(call.input); + const payload: Json = { title: input.title, ...(input.body !== undefined ? { body: input.body } : {}), ...(input.labels !== undefined ? { labels: input.labels } : {}) }; + return { repository: input.repository, path: `/repos/${input.repository}/issues`, payload, card: { repository: input.repository, ...payload } as Json, + target: input.repository, describe: `File this issue in ${input.repository} on GitHub` }; + } + const input = GITHUB_ISSUE_COMMENT_INPUT_SCHEMA.parse(call.input); + const payload: Json = { body: input.body }; + return { repository: input.repository, path: `/repos/${input.repository}/issues/${input.number}/comments`, payload, + card: { repository: input.repository, number: input.number, ...payload } as Json, target: `${input.repository}#${input.number}`, + describe: `Post this comment on ${input.repository}#${input.number} on GitHub` }; + } + + /** Canonical JSON with sorted keys, so an echoed card compares equal to the one shown. */ + const canonical = (value: unknown): string => JSON.stringify(value, (_key, item) => + item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item as Json).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0)) : item); + + async function write(turn: GithubToolsTurn, call: Extract): Promise { + const { tool } = call; + const ctx = turn.write; + // An autonomous or otherwise unbound turn has no approval surface and no policy: it never writes. + if (!ctx) return refusal(tool, "policy_denied", "no_write_surface", "GitHub writes are not available in this turn. Unattended work never writes to GitHub."); + const prepared = prepareWrite(call); + const visible = ctx.toolName(tool); + let tainted = true; + try { tainted = ctx.tainted(); } catch { /* Unknown taint is tainted. */ } + /** Records the decision. Only an approval's record is load-bearing: unrecorded, nothing is sent. */ + const decide = async (decision: "approved" | "declined" | "refused"): Promise => { + const recorded = canonical(prepared.card); + try { + await ctx.govern({ kind: "outward_action", payload: { tool: visible, input: recorded.slice(0, 8192), inputTruncated: recorded.length > 8192, + action: "gh_write", target: prepared.target, historyRewrite: false, tainted, decision, rule: null } }); + return true; + } catch (error) { + options.report?.(`GitHub write ${decision} not recorded: ${error instanceof Error ? error.message : String(error)}`); + return false; + } + }; + // The allow-list first: a repository it does not open never reaches a card or GitHub. + const allowance = githubWriteAllowance(ctx.repositories() ?? [], prepared.repository); + if (!allowance) { + await decide("refused"); + return refusal(tool, "policy_denied", "repository_not_allowed", + `${prepared.repository} is not open to GitHub writes. The governance policy's outward.github.repositories must list it (owner/repo or owner/*); nothing was sent.`); + } + if (ctx.posture !== "interactive") { + await decide("refused"); + return refusal(tool, "approval_declined", "voice_posture", "Voice cannot approve a GitHub write. Nothing was sent; ask for it in a typed conversation."); + } + const token = options.token(); + if (!token) return noCredential(tool); + const decision = await ctx.requestPermission({ toolUseId: `github-${crypto.randomUUID()}`, toolName: visible, kind: "command", input: prepared.card, + description: `${prepared.describe}, exactly as shown. It is sent once, in your name, through the host's GitHub credential, and cannot be undone from here.` + + (tainted ? " This conversation has read untrusted input; its content may have been shaped by it." : "") }); + // An edited card is a different write: it is refused, and the call must be made again as wanted, which rechecks it. + const edited = decision.behavior === "allow" && decision.updatedInput !== undefined && canonical(decision.updatedInput) !== canonical(prepared.card); + if (decision.behavior !== "allow" || edited) { + await decide("declined"); + return refusal(tool, "approval_declined", edited ? "edited" : "declined", edited + ? "The approval changed what would be sent, so nothing was sent. Make the call again with the content you want, to be approved as it is." + : "The user declined this GitHub write; nothing was sent."); + } + if (turn.signal?.aborted || !ctx.isCurrent()) { + await decide("refused"); + return refusal(tool, "upstream_error", "cancelled", "The turn ended before the write was sent; nothing was sent."); + } + if (!await decide("approved")) return refusal(tool, "unavailable", "recording_unavailable", "The approval could not be recorded, so nothing was sent."); + const { owner, repo } = parseGithubRepository(prepared.repository)!; + const created = record(await post(token, prepared.path, prepared.payload, turn.signal)); + if (tool === GITHUB_TOOL_NAMES.create) { + const number = integer(created?.number); + if (!created || !number) throw new GithubRefusal("upstream_error", "malformed", "GitHub accepted the issue but returned an unexpected answer."); + const result: GithubIssueCreatePayload = { kind: "issue_created", repository: `${owner}/${repo}`, number, + title: cut(text(created.title) ?? "", GITHUB_LIMITS.titleChars).text, labels: labels(created.labels).items.map(label => label.name), + created_at: requiredTime(created.created_at, new Date(now()).toISOString()), + html_url: githubDirectUrl(created.html_url, { owner, repo, number }, { kind: "issue" }) }; + return { ok: true, tool, result }; + } + const number = (call.input as { number: number }).number; + const id = integer(created?.id); + if (!created || !id) throw new GithubRefusal("upstream_error", "malformed", "GitHub accepted the comment but returned an unexpected answer."); + const result: GithubIssueCommentPayload = { kind: "comment_created", repository: `${owner}/${repo}`, number, comment_id: id, + created_at: requiredTime(created.created_at, new Date(now()).toISOString()), + html_url: githubDirectUrl(created.html_url, { owner, repo, number }, { kind: "comment", id }) }; + return { ok: true, tool, result }; + } return { async call(turn, call) { const { tool } = call; - if (tool === GITHUB_TOOL_NAMES.create || tool === GITHUB_TOOL_NAMES.comment) - return refusal(tool, "unavailable", "not_registered", "GitHub writes are not available on this host yet."); + if (tool === GITHUB_TOOL_NAMES.create || tool === GITHUB_TOOL_NAMES.comment) { + try { return await write(turn, call); } + catch (error) { + if (error instanceof GithubRefusal) return refusal(tool, error.code, error.reason, error.message); + if (error instanceof Error && error.name === "ZodError") return refusal(tool, "invalid_input", null, "The input does not match the tool's schema; nothing was sent."); + options.report?.(`GitHub tool ${tool} failed: ${error instanceof Error ? error.message : String(error)}`); + return refusal(tool, "upstream_error", null, "The GitHub write failed; it may not have been made."); + } + } const token = options.token(); - if (!token) return refusal(tool, "unavailable", "no_credential", "This host has no GitHub credential for its GitHub tools (BRAIN_UI_GITHUB_TOOLS_TOKEN). GITHUB_TOKEN is never used for them."); + if (!token) return noCredential(tool); try { if (tool === GITHUB_TOOL_NAMES.read) { const input = GITHUB_ISSUE_READ_INPUT_SCHEMA.parse(call.input); diff --git a/packages/ui-server/src/ws/bridge.ts b/packages/ui-server/src/ws/bridge.ts index 76e4dd1213..1788c1ccf7 100644 --- a/packages/ui-server/src/ws/bridge.ts +++ b/packages/ui-server/src/ws/bridge.ts @@ -15,6 +15,8 @@ import { createScratch } from "./bridge-capabilities/scratch.js"; import { createAttachmentRead } from "./bridge-capabilities/attachments.js"; import { createWebAccess } from "./bridge-capabilities/web.js"; import { createEffectiveSafety } from "../governance/effective-safety.js"; +import { sessionTaint } from "../governance/session-taint.js"; +import type { GithubOutwardAction } from "../github/host.js"; import { retainTurnSessionBinding } from "./bridge-session-binding.js"; export { emitTurnError } from "./bridge-capabilities/turn-error.js"; @@ -124,10 +126,33 @@ function applyExternalServices(ctx: BridgeContext, bridge: BackendBridge, transc approvals: { requestPermission: request => bridge.requestPermission(request) }, signal }, call); } // GitHub (#3797): the host holds the credential and records the session's - // taint; the turn, never the call, names principal and session. + // taint; the turn, never the call, names principal and session. Writes + // (#3798) take the allow-list from this turn's admitted policy, and their + // card from this bridge's own approval surface, so voice and revoked turns + // refuse as they do for every other card. No policy, no writes. if (host.githubTools) { const github = host.githubTools; - bridge.github = call => github.call({ turnId, principalId, sessionId: () => transcript.collectedSessionId ?? turn.sessionId ?? null, signal }, call); + const sessionId = () => transcript.collectedSessionId ?? turn.sessionId ?? null; + const posture = work?.posture === "voice" ? "voice" as const : "interactive" as const; + const write = { + repositories: () => governance?.policy.policy.outward?.github?.repositories ?? null, + posture, + requestPermission: (request: Parameters[0]) => bridge.requestPermission(request), + toolName, + tainted: () => { + const writes = host.activity?.governanceWrites, db = host.activity?.governanceDb; + return writes ? writes.taint(turnId, sessionId()) !== null : db ? sessionTaint(db, turnId, sessionId()) !== null : false; + }, + isCurrent: () => !signal.aborted && isAuthorized(), + // Awaited where the store can say whether it committed, so an approval that is not recorded sends nothing. + govern: async (event: GithubOutwardAction) => { + const input = { ...event, turnId, sessionId: sessionId(), actor: posture, model: mainModel?.current() ?? null, profile: workerProfile?.actualProfile ?? null } as never; + const writes = host.activity?.governanceWrites; + if (writes) { await writes.record(input); return; } + host.catalog.recordGovernanceEvent?.(input); + }, + }; + bridge.github = call => github.call({ turnId, principalId, sessionId, signal, write }, call); } } diff --git a/packages/ui-server/tests/fixtures/github-host-fixture.ts b/packages/ui-server/tests/fixtures/github-host-fixture.ts index 2c5fbab6d0..23886d58fc 100644 --- a/packages/ui-server/tests/fixtures/github-host-fixture.ts +++ b/packages/ui-server/tests/fixtures/github-host-fixture.ts @@ -3,7 +3,10 @@ * `odysseus/ithaca`, with an issue (#7) and a pull request (#8), shaped like * the real responses (issue, pull, comments, reviews, commits, check runs, * combined status and issue search). It records every request with the - * authorization it carried. Keyless: the token is a synthetic sentinel. + * authorization it carried, and a write's body. Writes (#3798): an issue + * filed in any repository, and a comment on any issue, answer 201 like + * GitHub, so a refusal proves itself by what never arrived. Keyless: the + * token is a synthetic sentinel. */ export const GITHUB_TOOLS_SENTINEL = "odysseus-github-tools-sentinel-token"; export const GENERIC_GITHUB_SENTINEL = "odysseus-generic-github-sentinel-token"; @@ -29,7 +32,7 @@ export interface FakeGithubOptions { export interface FakeGithub { origin: string; - seen: Array<{ method: string; path: string; search: string; authorization: string | null }>; + seen: Array<{ method: string; path: string; search: string; authorization: string | null; body: string | null }>; stop(): void; } @@ -61,11 +64,29 @@ export function fakeGithub(options: FakeGithubOptions = {}): FakeGithub { const commits = COMMIT_SHAS.map((sha, index) => ({ sha, html_url: `${WEB}/commit/${sha}`, author: index ? null : telemachus, commit: { message: `Wax the string ${index + 1}`, author: { name: "Telemachus", date: at(2 + index) } } })); const json = (body: unknown, init?: ResponseInit) => Response.json(body, init); - const server = Bun.serve({ hostname: "127.0.0.1", port: 0, fetch(request) { + let filed = 41, commented = 77_000; + const server = Bun.serve({ hostname: "127.0.0.1", port: 0, async fetch(request) { const url = new URL(request.url); - seen.push({ method: request.method, path: url.pathname, search: url.search, authorization: request.headers.get("authorization") }); + const body = request.method === "GET" ? null : await request.text(); + seen.push({ method: request.method, path: url.pathname, search: url.search, authorization: request.headers.get("authorization"), body }); const overridden = options.override?.(url.pathname, url.searchParams); if (overridden) return overridden; + if (request.method === "POST") { + const sent = JSON.parse(body ?? "{}") as { title?: string; body?: string; labels?: string[] }; + const created = /^\/repos\/([^/]+)\/([^/]+)\/issues$/.exec(url.pathname); + if (created) { + const number = ++filed; + return json({ number, title: sent.title, state: "open", user: penelope, body: sent.body ?? null, labels: (sent.labels ?? []).map(label), + created_at: at(12), updated_at: at(12), html_url: `https://github.com/${created[1]}/${created[2]}/issues/${number}` }, { status: 201 }); + } + const comment = /^\/repos\/([^/]+)\/([^/]+)\/issues\/(\d+)\/comments$/.exec(url.pathname); + if (comment) { + const id = ++commented; + return json({ id, user: penelope, body: sent.body, created_at: at(12), updated_at: at(12), + html_url: `https://github.com/${comment[1]}/${comment[2]}/issues/${comment[3]}#issuecomment-${id}` }, { status: 201 }); + } + return json({ message: "Not Found" }, { status: 404 }); + } const page = Number(url.searchParams.get("page") ?? "1"), perPage = Number(url.searchParams.get("per_page") ?? "30"); switch (url.pathname) { case "/repos/odysseus/ithaca/issues/7": return json(issue); diff --git a/packages/ui-server/tests/github-tools-host.test.ts b/packages/ui-server/tests/github-tools-host.test.ts index a9a9db7f2a..fa70dd890e 100644 --- a/packages/ui-server/tests/github-tools-host.test.ts +++ b/packages/ui-server/tests/github-tools-host.test.ts @@ -53,12 +53,6 @@ describe("the dedicated credential", () => { for (const request of fake.seen) expect(request.authorization, `GITHUB_DEDICATED_BEARER ${request.path}`).toBe(`Bearer ${GITHUB_TOOLS_SENTINEL}`); }); - test("the write tools are declared but answer unavailable until their approval cards exist", async () => { - const { fake, github } = host(); - const result = await github.call(turn, { tool: "brain_github_issue_create", input: { repository: "odysseus/ithaca", title: "Bar the doors" } }); - expect(result).toMatchObject({ ok: false, error: { code: "unavailable", reason: "not_registered" } }); - expect(fake.seen).toEqual([]); - }); }); describe("issue and pull request reads", () => { diff --git a/packages/ui-server/tests/github-write-tools.test.ts b/packages/ui-server/tests/github-write-tools.test.ts new file mode 100644 index 0000000000..49533e59ac --- /dev/null +++ b/packages/ui-server/tests/github-write-tools.test.ts @@ -0,0 +1,222 @@ +/** + * The host GitHub write tools (#3798) against a loopback stand-in for the + * GitHub API: the turn's policy allow-list decides before any card, an + * allowed write raises one card with exactly what will be sent, only an + * unedited allow sends it, once, and every decision is recorded as an + * `outward_action`. The stand-in accepts any write, so a refusal is proven + * by the requests that never arrived. + */ +import { afterEach, describe, expect, test } from "bun:test"; +import { GITHUB_RESULT_SCHEMAS, type GithubToolCall, type GithubToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; +import type { PermissionDecision, PermissionRequest } from "@schlessera/brain-ui-sdk/server"; +import { createGithubToolsHost, type GithubOutwardAction, type GithubToolsHostOptions, type GithubToolsTurn, type GithubWriteTurn } from "../src/github/host.js"; +import { GITHUB_TOOLS_SENTINEL, fakeGithub, standInFetch, type FakeGithub, type FakeGithubOptions } from "./fixtures/github-host-fixture.js"; + +const stops: FakeGithub[] = []; +afterEach(() => { for (const fake of stops.splice(0)) fake.stop(); }); + +const CREATE = { tool: "brain_github_issue_create", input: { repository: "odysseus/ithaca", title: "Bar the hall doors", body: "Before the contest of the bow.", labels: ["household", "urgent"] } } as const satisfies GithubToolCall; +const COMMENT = { tool: "brain_github_issue_comment", input: { repository: "odysseus/ithaca", number: 7, body: "The stores are counted again." } } as const satisfies GithubToolCall; + +interface Harness { + fake: FakeGithub; cards: PermissionRequest[]; recorded: GithubOutwardAction[]; + call(call: GithubToolCall, overrides?: Partial, turnOverrides?: Partial): Promise; +} + +function harness(answer: (request: PermissionRequest) => PermissionDecision | Promise = () => ({ behavior: "allow" }), + options: { repositories?: readonly string[] | null; host?: Partial; github?: FakeGithubOptions } = {}): Harness { + const fake = fakeGithub(options.github); stops.push(fake); + const cards: PermissionRequest[] = [], recorded: GithubOutwardAction[] = []; + const github = createGithubToolsHost({ token: () => GITHUB_TOOLS_SENTINEL, fetch: standInFetch(fake), now: () => Date.parse("2026-07-12T12:00:00Z"), + untrusted: async () => {}, ...options.host }); + return { fake, cards, recorded, call: (call, overrides = {}, turnOverrides = {}) => { + const write: GithubWriteTurn = { + repositories: () => options.repositories === undefined ? ["odysseus/ithaca"] : options.repositories, + posture: "interactive", requestPermission: async request => { cards.push(request); return answer(request); }, + toolName: name => `mcp__brain-ui__${name}`, tainted: () => false, isCurrent: () => true, + govern: event => { recorded.push(event); }, ...overrides, + }; + return github.call({ turnId: "turn-ithaca", principalId: "principal-penelope", sessionId: () => "sess-ithaca", write, ...turnOverrides }, call); + } }; +} +const writes = (fake: FakeGithub) => fake.seen.filter(request => request.method !== "GET"); +const parsed = (result: GithubToolResult) => GITHUB_RESULT_SCHEMAS[result.tool].parse(result); + +describe("an allowed write", () => { + test("raises one card with the exact repository, title, body and labels, and Allow files exactly one issue", async () => { + const h = harness(); + const result = parsed(await h.call(CREATE)); + expect(h.cards.length, "GITHUB_WRITE_ONE_CARD").toBe(1); + expect(h.cards[0], "GITHUB_WRITE_CARD_EXACT").toMatchObject({ toolName: "mcp__brain-ui__brain_github_issue_create", kind: "command", + input: { repository: "odysseus/ithaca", title: "Bar the hall doors", body: "Before the contest of the bow.", labels: ["household", "urgent"] } }); + expect(Object.keys(h.cards[0]!.input).sort()).toEqual(["body", "labels", "repository", "title"]); + expect(writes(h.fake), "GITHUB_WRITE_EXACTLY_ONE_REQUEST").toHaveLength(1); + const [sent] = writes(h.fake); + expect(sent).toMatchObject({ method: "POST", path: "/repos/odysseus/ithaca/issues", authorization: `Bearer ${GITHUB_TOOLS_SENTINEL}` }); + // What was sent is what the card showed, the repository aside. + expect(JSON.parse(sent!.body!), "GITHUB_WRITE_SENT_AS_SHOWN").toEqual({ title: "Bar the hall doors", body: "Before the contest of the bow.", labels: ["household", "urgent"] }); + expect(result).toEqual({ ok: true, tool: "brain_github_issue_create", result: { kind: "issue_created", repository: "odysseus/ithaca", number: 42, + title: "Bar the hall doors", labels: ["household", "urgent"], created_at: "2026-07-12T09:00:00Z", html_url: "https://github.com/odysseus/ithaca/issues/42" } }); + expect(h.recorded.map(event => event.payload.decision), "GITHUB_WRITE_RECORDED_APPROVED").toEqual(["approved"]); + expect(h.recorded[0]!.payload).toMatchObject({ tool: "mcp__brain-ui__brain_github_issue_create", action: "gh_write", target: "odysseus/ithaca", historyRewrite: false, tainted: false, rule: null }); + expect(JSON.parse(h.recorded[0]!.payload.input)).toEqual(h.cards[0]!.input); + }); + + test("a trimmed title is shown and sent trimmed, and an absent body or labels is neither shown nor sent", async () => { + const h = harness(); + await h.call({ tool: "brain_github_issue_create", input: { repository: "odysseus/ithaca", title: " Count the suitors " } }); + expect(h.cards[0]!.input).toEqual({ repository: "odysseus/ithaca", title: "Count the suitors" }); + expect(JSON.parse(writes(h.fake)[0]!.body!)).toEqual({ title: "Count the suitors" }); + }); + + test("a comment raises one card with the repository, number and body, and Allow posts exactly one comment", async () => { + const h = harness(); + const result = parsed(await h.call(COMMENT)); + expect(h.cards.map(card => card.input), "GITHUB_COMMENT_CARD_EXACT").toEqual([{ repository: "odysseus/ithaca", number: 7, body: "The stores are counted again." }]); + expect(writes(h.fake).map(request => [request.path, JSON.parse(request.body!)])).toEqual([["/repos/odysseus/ithaca/issues/7/comments", { body: "The stores are counted again." }]]); + expect(result).toEqual({ ok: true, tool: "brain_github_issue_comment", result: { kind: "comment_created", repository: "odysseus/ithaca", number: 7, + comment_id: 77001, created_at: "2026-07-12T09:00:00Z", html_url: "https://github.com/odysseus/ithaca/issues/7#issuecomment-77001" } }); + expect(h.recorded.map(event => [event.payload.target, event.payload.decision])).toEqual([["odysseus/ithaca#7", "approved"]]); + }); + + test("a tainted session's card says so, and its record carries the taint", async () => { + const h = harness(); + await h.call(CREATE, { tainted: () => true }); + expect(h.cards[0]!.description).toContain("untrusted input"); + expect(h.recorded[0]!.payload.tainted).toBe(true); + const unknown = harness(); + await unknown.call(CREATE, { tainted: () => { throw new Error("taint store unavailable"); } }); + expect(unknown.recorded[0]!.payload.tainted, "GITHUB_UNKNOWN_TAINT_IS_TAINTED").toBe(true); + }); +}); + +describe("a write that is not approved as shown sends nothing", () => { + test("Deny sends nothing and is recorded as declined", async () => { + const h = harness(() => ({ behavior: "deny", message: "Not today." })); + const result = await h.call(CREATE); + expect(result, "GITHUB_DENY_REFUSED").toMatchObject({ ok: false, error: { code: "approval_declined", reason: "declined" } }); + expect(h.cards).toHaveLength(1); + expect(writes(h.fake), "GITHUB_DENY_SENDS_NOTHING").toEqual([]); + expect(h.recorded.map(event => event.payload.decision)).toEqual(["declined"]); + }); + + test("an approval that changed the input sends nothing; one that echoes it unchanged sends it", async () => { + for (const [label, updatedInput] of [ + ["another repository", { ...CREATE.input, repository: "odysseus/argo" }], + ["another title", { ...CREATE.input, title: "Open the hall doors" }], + ["an added label", { ...CREATE.input, labels: ["household", "urgent", "contest"] }], + ] as const) { + const h = harness(() => ({ behavior: "allow", updatedInput })); + const result = await h.call(CREATE); + expect(result, `GITHUB_EDITED_REFUSED ${label}`).toMatchObject({ ok: false, error: { code: "approval_declined", reason: "edited" } }); + expect(writes(h.fake), `GITHUB_EDITED_SENDS_NOTHING ${label}`).toEqual([]); + expect(h.recorded.map(event => event.payload.decision)).toEqual(["declined"]); + } + const echoed = harness(request => ({ behavior: "allow", updatedInput: Object.fromEntries(Object.entries(request.input).reverse()) })); + expect((await echoed.call(CREATE)).ok, "GITHUB_ECHOED_INPUT_SENDS").toBe(true); + expect(writes(echoed.fake)).toHaveLength(1); + }); + + test("a turn that ended or lost its authority while the card was open sends nothing", async () => { + const controller = new AbortController(); + const aborted = harness(() => { controller.abort(); return { behavior: "allow" }; }); + expect(await aborted.call(CREATE, {}, { signal: controller.signal })).toMatchObject({ ok: false, error: { reason: "cancelled" } }); + expect(writes(aborted.fake), "GITHUB_ABORTED_SENDS_NOTHING").toEqual([]); + let current = true; + const revoked = harness(() => { current = false; return { behavior: "allow" }; }); + expect(await revoked.call(CREATE, { isCurrent: () => current })).toMatchObject({ ok: false, error: { reason: "cancelled" } }); + expect(writes(revoked.fake), "GITHUB_REVOKED_SENDS_NOTHING").toEqual([]); + expect(revoked.recorded.map(event => event.payload.decision)).toEqual(["refused"]); + }); + + test("an approval whose record fails sends nothing", async () => { + const h = harness(); + const result = await h.call(CREATE, { govern: event => { if (event.payload.decision === "approved") throw new Error("governance store unavailable"); } }); + expect(result).toMatchObject({ ok: false, error: { code: "unavailable", reason: "recording_unavailable" } }); + expect(writes(h.fake), "GITHUB_UNRECORDED_SENDS_NOTHING").toEqual([]); + }); + + test("a failed or redirected write is sent once and never retried or followed", async () => { + for (const [label, answer, reason] of [ + ["server error", () => Response.json({ message: "The loom is tangled" }, { status: 502 }), "http_502"], + ["redirect", () => new Response(null, { status: 307, headers: { location: "/repos/odysseus/argo/issues" } }), "http_307"], + ] as const) { + const h = harness(undefined, { github: { override: path => path === "/repos/odysseus/ithaca/issues" ? answer() : undefined } }); + expect(await h.call(CREATE), `GITHUB_WRITE_FAILED ${label}`).toMatchObject({ ok: false, error: { code: "upstream_error", reason } }); + expect(writes(h.fake).map(request => request.path), `GITHUB_WRITE_NOT_RETRIED ${label}`).toEqual(["/repos/odysseus/ithaca/issues"]); + } + }); +}); + +describe("the repository allow-list", () => { + test("a write outside the list is refused before any card, names the policy key, sends nothing and is recorded as refused", async () => { + for (const call of [{ ...CREATE, input: { ...CREATE.input, repository: "circe/aiaia" } }, { ...COMMENT, input: { ...COMMENT.input, repository: "odysseus/argo" } }] as GithubToolCall[]) { + const h = harness(); + const result = parsed(await h.call(call)); + expect(result, `GITHUB_OUTSIDE_LIST_REFUSED ${call.tool}`).toMatchObject({ ok: false, error: { code: "policy_denied", reason: "repository_not_allowed" } }); + if (result.ok) throw new Error("unreachable"); + expect(result.error.message).toContain("outward.github.repositories"); + expect(h.cards, `GITHUB_OUTSIDE_LIST_NO_CARD ${call.tool}`).toEqual([]); + expect(h.fake.seen, `GITHUB_OUTSIDE_LIST_NOTHING_SENT ${call.tool}`).toEqual([]); + expect(h.recorded.map(event => event.payload.decision)).toEqual(["refused"]); + } + }); + + test("the exact and owner/* forms reach the card, the owner and repository compare without case", async () => { + for (const [repositories, repository] of [ + [["odysseus/ithaca"], "odysseus/ithaca"], [["odysseus/*"], "odysseus/argo"], [["Odysseus/*"], "odysseus/ithaca"], + [["odysseus/Ithaca"], "ODYSSEUS/ithaca"], [["circe/aiaia", "odysseus/*"], "odysseus/ithaca"], + ] as const) { + const h = harness(undefined, { repositories }); + const result = await h.call({ ...CREATE, input: { ...CREATE.input, repository } }); + expect(result.ok, `GITHUB_ALLOWED ${repositories.join(",")} ${repository}`).toBe(true); + expect(h.cards, `GITHUB_ALLOWED_CARD ${repositories.join(",")} ${repository}`).toHaveLength(1); + } + // One owner's wildcard is not another's, and an exact entry is not a prefix. + for (const [repositories, repository] of [[["odysseus/*"], "circe/aiaia"], [["odysseus/ithaca"], "odysseus/ithaca-archive"], [["odysseus/ithaca"], "odysseu/ithaca"]] as const) { + const h = harness(undefined, { repositories }); + expect((await h.call({ ...CREATE, input: { ...CREATE.input, repository } })).ok, `GITHUB_NOT_ALLOWED ${repositories.join(",")} ${repository}`).toBe(false); + expect(h.cards).toEqual([]); + expect(h.fake.seen).toEqual([]); + } + }); + + test("an absent or empty list, or no governance policy at all, refuses every write", async () => { + for (const repositories of [null, []] as const) { + const h = harness(undefined, { repositories }); + for (const call of [CREATE, COMMENT] as GithubToolCall[]) { + expect(await h.call(call), `GITHUB_NO_LIST_REFUSED ${JSON.stringify(repositories)} ${call.tool}`).toMatchObject({ ok: false, error: { code: "policy_denied", reason: "repository_not_allowed" } }); + } + expect(h.cards).toEqual([]); + expect(h.fake.seen).toEqual([]); + } + }); + + test("no credential answers unavailable after the allow-list and before any card", async () => { + const h = harness(undefined, { host: { token: () => undefined } }); + expect(await h.call(CREATE)).toMatchObject({ ok: false, error: { code: "unavailable", reason: "no_credential" } }); + expect(h.cards).toEqual([]); + expect(h.fake.seen).toEqual([]); + }); +}); + +describe("postures that never approve", () => { + test("voice cannot approve a write: it is refused before any card, even when the surface would allow it", async () => { + const h = harness(() => ({ behavior: "allow" })); + for (const call of [CREATE, COMMENT] as GithubToolCall[]) { + expect(await h.call(call, { posture: "voice" }), `GITHUB_VOICE_REFUSED ${call.tool}`).toMatchObject({ ok: false, error: { code: "approval_declined", reason: "voice_posture" } }); + } + expect(h.cards, "GITHUB_VOICE_NO_CARD").toEqual([]); + expect(h.fake.seen, "GITHUB_VOICE_NOTHING_SENT").toEqual([]); + expect(h.recorded.map(event => event.payload.decision)).toEqual(["refused", "refused"]); + }); + + test("a turn without a write surface, as an autonomous one, cannot dispatch a write", async () => { + const h = harness(); + for (const call of [CREATE, COMMENT] as GithubToolCall[]) { + expect(await h.call(call, {}, { write: undefined }), `GITHUB_NO_WRITE_SURFACE ${call.tool}`).toMatchObject({ ok: false, error: { code: "policy_denied", reason: "no_write_surface" } }); + } + expect(h.cards).toEqual([]); + expect(h.fake.seen).toEqual([]); + }); +}); diff --git a/packages/ui-server/tests/ws-github.test.ts b/packages/ui-server/tests/ws-github.test.ts index cc4f4dfb56..b795fa0774 100644 --- a/packages/ui-server/tests/ws-github.test.ts +++ b/packages/ui-server/tests/ws-github.test.ts @@ -5,7 +5,9 @@ * receives the dedicated credential; the session's taint is recorded as * `github_result`; no client frame and no subprocess environment carries * the credential; with only `GITHUB_TOKEN` set the tools answer - * `unavailable` and send nothing. + * `unavailable` and send nothing. Writes (#3798) take their allow-list from + * the turn's admitted governance policy and their card from the turn's own + * approval surface, and are recorded as `outward_action`. * * Keyless and offline: the fixed API origin is routed to a loopback fake * after the network preload; the tokens are synthetic sentinels. @@ -14,7 +16,7 @@ import { installFixtureNativeStartupViews } from "./helpers/fixture-native-start installFixtureNativeStartupViews(); import { createNativeJournalFixture } from "./helpers/native-journal-fixture.js"; import { expect, test } from "bun:test"; -import { mkdtemp, rm } from "node:fs/promises"; +import { mkdir, mkdtemp, rm, writeFile } from "node:fs/promises"; import { tmpdir } from "node:os"; import { resolve } from "node:path"; import type { GithubToolResult } from "@schlessera/brain-ui-sdk/tool-contracts"; @@ -32,9 +34,14 @@ import { GENERIC_GITHUB_SENTINEL, GITHUB_TOOLS_SENTINEL, fakeGithub, routeGithub const SESSION = "sess-ithaca-github"; -async function hostedTurn(backendId: "pi" | "claude", env: Record, script: (github: (tool: string, input: unknown) => Promise) => Promise) { +async function hostedTurn(backendId: "pi" | "claude", env: Record, script: (github: (tool: string, input: unknown) => Promise) => Promise, + options: { policy?: string; answer?: (request: Record) => Record } = {}) { const root = await mkdtemp(resolve(tmpdir(), "odysseus-host-github-")), brain = resolve(root, "brain"); await createFixtureBrain(resolve(import.meta.dir, "../../.."), brain); + if (options.policy !== undefined) { + await mkdir(resolve(brain, "context/policies"), { recursive: true }); + await writeFile(resolve(brain, "context/policies/governance.md"), `---\nschema_version: 1\n${options.policy}\n---\nIthaca's outward rules.\n`); + } const fake = fakeGithub(), restore = routeGithubApi(fake); const names = ["BRAIN_UI_GITHUB_TOOLS_TOKEN", "GITHUB_TOKEN"] as const; const previous = Object.fromEntries(names.map(name => [name, process.env[name]])); @@ -68,11 +75,22 @@ async function hostedTurn(backendId: "pi" | "claude", env: Record { sent.push(text); }, close() {}, readyState: 1 } as WSContext; await handlers.onOpen(undefined as never, ws); handlers.onMessage({ data: JSON.stringify({ type: "chat_message", text: "Look up the suitors issue", requestId: "github-request" }) } as MessageEvent, ws); - const until = Date.now() + 45_000; - while (!finished || app.isTurnActive()) { if (Date.now() > until) throw new Error(`turn did not finish: ${sent.join("\n")}`); await Bun.sleep(10); } + const until = Date.now() + 45_000, answered = new Set(), cards: Array> = []; + while (!finished || app.isTurnActive()) { + if (Date.now() > until) throw new Error(`turn did not finish: ${sent.join("\n")}`); + // Answer each approval card the client is shown, as the user would. + for (const frame of sent.map(text => JSON.parse(text) as Record)) { + if (frame.type !== "tool_approval_request" || answered.has(String(frame.toolUseId))) continue; + answered.add(String(frame.toolUseId)); cards.push(frame); + const answer = options.answer?.(frame) ?? { type: "tool_denial", message: "No card was expected." }; + handlers.onMessage({ data: JSON.stringify({ toolUseId: frame.toolUseId, turnId: frame.turnId, channel: "card", ...answer }) } as MessageEvent, ws); + } + await Bun.sleep(10); + } if (scriptError) throw scriptError; const taint = queryGovernanceEvents(app.db, { kinds: ["taint"], limit: 10 }).sort((a, b) => a.id - b.id); - return { root, fake, sent, taint, workerEnvs }; + const outward = queryGovernanceEvents(app.db, { kinds: ["outward_action"], limit: 10 }).sort((a, b) => a.id - b.id); + return { root, fake, sent, taint, outward, cards, workerEnvs }; } finally { await app.close(); broker.close(); await native.close(); restore(); fake.stop(); @@ -112,3 +130,37 @@ test("with only GITHUB_TOKEN set the read tools answer unavailable, send nothing expect(outcome.taint).toEqual([]); } finally { await rm(outcome.root, { recursive: true, force: true }); } }, 60_000); + +const POLICY = 'outward: { github: { repositories: ["odysseus/ithaca"] } }'; +const ISSUE = { repository: "odysseus/ithaca", title: "Bar the hall doors", body: "Before the contest of the bow.", labels: ["household"] }; + +for (const backendId of ["pi", "claude"] as const) test(`a ${backendId} turn files an allowed issue after one card from the turn's policy, and is refused outside it before any card`, async () => { + const results: GithubToolResult[] = []; + const outcome = await hostedTurn(backendId, { BRAIN_UI_GITHUB_TOOLS_TOKEN: GITHUB_TOOLS_SENTINEL }, async github => { + results.push(await github("brain_github_issue_create", { ...ISSUE, repository: "circe/aiaia" })); + results.push(await github("brain_github_issue_create", ISSUE)); + }, { policy: POLICY, answer: () => ({ type: "tool_approval" }) }); + try { + expect(results[0], "GITHUB_APP_OUTSIDE_LIST_REFUSED").toMatchObject({ ok: false, error: { code: "policy_denied", reason: "repository_not_allowed" } }); + expect(results[1], "GITHUB_APP_ALLOWED_WRITE").toMatchObject({ ok: true, result: { kind: "issue_created", repository: "odysseus/ithaca", number: 42 } }); + expect(outcome.cards.length, "GITHUB_APP_ONE_CARD").toBe(1); + expect(outcome.cards[0], "GITHUB_APP_CARD_EXACT").toMatchObject({ input: ISSUE }); + expect(outcome.fake.seen.map(request => [request.method, request.path]), "GITHUB_APP_ONE_REQUEST").toEqual([["POST", "/repos/odysseus/ithaca/issues"]]); + expect(outcome.outward.map(event => ({ session: event.sessionId, action: event.payload.action, target: event.payload.target, decision: event.payload.decision })), "GITHUB_APP_OUTWARD_RECORDED").toEqual([ + { session: SESSION, action: "gh_write", target: "circe/aiaia", decision: "refused" }, { session: SESSION, action: "gh_write", target: "odysseus/ithaca", decision: "approved" }]); + for (const event of outcome.outward) GOVERNANCE_EVENT_SCHEMAS.outward_action.payload.parse(event.payload); + } finally { await rm(outcome.root, { recursive: true, force: true }); } +}, 60_000); + +test("without a governance policy entry a write is refused before any card and sends nothing", async () => { + const results: GithubToolResult[] = []; + const outcome = await hostedTurn("claude", { BRAIN_UI_GITHUB_TOOLS_TOKEN: GITHUB_TOOLS_SENTINEL }, async github => { + results.push(await github("brain_github_issue_create", ISSUE)); + results.push(await github("brain_github_issue_comment", { repository: "odysseus/ithaca", number: 7, body: "Counted." })); + }, { answer: () => ({ type: "tool_approval" }) }); + try { + for (const result of results) expect(result, "GITHUB_APP_NO_LIST_REFUSED").toMatchObject({ ok: false, error: { code: "policy_denied", reason: "repository_not_allowed" } }); + expect(outcome.cards).toEqual([]); + expect(outcome.fake.seen).toEqual([]); + } finally { await rm(outcome.root, { recursive: true, force: true }); } +}, 60_000); diff --git a/scripts/turn-surface-fixture.ts b/scripts/turn-surface-fixture.ts index 0eadf3ecee..ac2e58d166 100644 --- a/scripts/turn-surface-fixture.ts +++ b/scripts/turn-surface-fixture.ts @@ -30,7 +30,8 @@ export const STABLE_BRIDGE_ROSTER = [ "brain_apify_discover", "brain_apify_inspect", "brain_apify_prepare", "brain_apify_results", "brain_apify_revoke", "brain_apify_run", "brain_apify_status", "brain_archive", "brain_compute_cancel", "brain_compute_collect", "brain_compute_health", "brain_compute_plan", - "brain_compute_run", "brain_compute_status", "brain_github_issue_read", "brain_github_issue_search", + "brain_compute_run", "brain_compute_status", "brain_github_issue_comment", "brain_github_issue_create", + "brain_github_issue_read", "brain_github_issue_search", "brain_read_base", "brain_update", "complete_share", "edit_file", "get_current_location", "inbox_add", "inbox_get", "inbox_list", "propose_policy_change", "query_activity", "read_attachment", "reference_source", "reference_worktree", diff --git a/tests/installed-turn-surface.test.ts b/tests/installed-turn-surface.test.ts index 1a8c7b7714..11b8b8f7de 100644 --- a/tests/installed-turn-surface.test.ts +++ b/tests/installed-turn-surface.test.ts @@ -30,12 +30,12 @@ test("actual installed CLI request preserves shipped deferred core tools, eager "mcp__brain__brain_list", "mcp__brain__brain_read", "mcp__brain__brain_read_many", "mcp__brain__brain_search", "mcp__brain__brain_update", ]); // 24 before the six external compute bridge tools (#3108), the ten fixed Apify bridge tools (#3162), read_attachment (#3154) - // and the two host GitHub read tools (#3797). - expect(capture.request.tools.filter(tool => tool.name.startsWith("mcp__brain-ui__"))).toHaveLength(43); + // and the four host GitHub tools, two reads (#3797) and two writes (#3798). + expect(capture.request.tools.filter(tool => tool.name.startsWith("mcp__brain-ui__"))).toHaveLength(45); for (const name of ["inbox_list", "inbox_get", "inbox_add", "resolve_action", "complete_share", "turn_temp", "reference_source", "reference_worktree", "brain_compute_health", "brain_compute_plan", "brain_compute_run", "brain_compute_status", "brain_compute_cancel", "brain_compute_collect", "brain_apify_availability", "brain_apify_approvals", "brain_apify_revoke", "brain_apify_discover", "brain_apify_inspect", "brain_apify_prepare", "brain_apify_run", "brain_apify_status", "brain_apify_results", "brain_apify_abort", - "read_attachment", "brain_github_issue_read", "brain_github_issue_search"]) { + "read_attachment", "brain_github_issue_read", "brain_github_issue_search", "brain_github_issue_create", "brain_github_issue_comment"]) { const tool = capture.request.tools.find(tool => tool.name === `mcp__brain-ui__${name}`); expect(tool?.input_schema).toBeDefined(); expect(tool?.defer_loading).not.toBe(true);