Skip to content
1,330 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1//! Run credentials: the least-privilege tokens a sandbox works with.
2//!
3//! Every sandbox run gets its own tokens, bound to the run, its repository
4//! (and the pull request's fork), what that kind of run needs to do, and an
5//! expiry no later than the run's timeout. Each carries a composite
6//! identity: an agent acting on behalf of the person who started the work.
7//! What it may do is the intersection of the two: the run's scope, and what
8//! that person may do right now.
9//!
10//! The policy lives here, as pure functions, so that identity (which mints
11//! the tokens), the API (which serves REST and MCP) and repos (which serves
12//! git) all enforce the same rules, and so the rules can be tested.
13
14use serde::{Deserialize, Serialize};
15
16use crate::identity::AgentScope;
17use crate::repos::RepoPath;
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look18use crate::access::{BasePermission, RepoGrant, RepoRole};
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API19use crate::{Membership, PrincipalKind, Role, User};
20
21/// What a run does, as far as its credentials are concerned. The same names
22/// as [`crate::agents::RunKind`], plus `deploy`, a build of one commit.
23#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
24#[serde(rename_all = "snake_case")]
25pub enum RunCredentialKind {
26 Implement,
27 Revise,
28 Review,
29 Answer,
30 Update,
31 Plan,
32 Checks,
33 Queue,
34 Mergecheck,
35 Deploy,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily36 /// A security update: raising one package's version in its lockfiles
37 /// and pushing that to a branch of its own. Not an agent.
38 Bump,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API39}
40
41impl RunCredentialKind {
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily42 pub const ALL: [RunCredentialKind; 11] = [
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API43 RunCredentialKind::Implement,
44 RunCredentialKind::Revise,
45 RunCredentialKind::Review,
46 RunCredentialKind::Answer,
47 RunCredentialKind::Update,
48 RunCredentialKind::Plan,
49 RunCredentialKind::Checks,
50 RunCredentialKind::Queue,
51 RunCredentialKind::Mergecheck,
52 RunCredentialKind::Deploy,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily53 RunCredentialKind::Bump,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API54 ];
55
56 pub fn as_str(self) -> &'static str {
57 match self {
58 RunCredentialKind::Implement => "implement",
59 RunCredentialKind::Revise => "revise",
60 RunCredentialKind::Review => "review",
61 RunCredentialKind::Answer => "answer",
62 RunCredentialKind::Update => "update",
63 RunCredentialKind::Plan => "plan",
64 RunCredentialKind::Checks => "checks",
65 RunCredentialKind::Queue => "queue",
66 RunCredentialKind::Mergecheck => "mergecheck",
67 RunCredentialKind::Deploy => "deploy",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily68 RunCredentialKind::Bump => "bump",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API69 }
70 }
71
72 /// Whether the run works on one pull request, whose session and
73 /// readiness it reports.
74 fn works_on_a_pull(self) -> bool {
75 matches!(
76 self,
77 RunCredentialKind::Implement
78 | RunCredentialKind::Revise
79 | RunCredentialKind::Answer
80 | RunCredentialKind::Update
81 )
82 }
83}
84
85/// Which part of a sandbox a credential is for.
86#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "snake_case")]
88pub enum CredentialUse {
89 /// g1t's runner: cloning, pushing the result, recording the session.
90 /// It acts as the person downstream, so that what it pushes and records
91 /// is theirs, within the run's scope.
92 Runner,
93 /// The agent's own tools, over MCP. It acts as the agent.
94 Tools,
95}
96
97impl CredentialUse {
98 pub fn as_str(self) -> &'static str {
99 match self {
100 CredentialUse::Runner => "runner",
101 CredentialUse::Tools => "tools",
102 }
103 }
104}
105
106/// A repository a run may push to, and the one branch, if only one.
107#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
108pub struct GitGrant {
109 pub repo: RepoPath,
110 /// Null: any branch. A pull request's fork is its own repository, so
111 /// the whole of it is the pull request's.
112 #[serde(default)]
113 pub branch: Option<String>,
114}
115
116/// What binds an agent's token to one run. Absent on agent tokens made
117/// before run credentials, which keep working for the API only.
118#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
119#[serde(rename_all = "camelCase")]
120pub struct RunBinding {
121 pub kind: RunCredentialKind,
122 #[serde(rename = "use")]
123 pub usage: CredentialUse,
124 /// The agent run, once the sandbox has recorded it.
125 #[serde(default)]
126 pub run_id: Option<String>,
127 /// The pull request the run works on, for the kinds that work on one.
128 #[serde(default)]
129 pub number: Option<u32>,
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent130 /// The agent's name, such as `g1t`.
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API131 pub agent: String,
132 /// Repositories it may clone and fetch, besides those it may push to.
133 #[serde(default)]
134 pub read: Vec<RepoPath>,
135 /// Where it may push.
136 #[serde(default)]
137 pub push: Vec<GitGrant>,
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily138 /// g1t's own run (a security update, an agent g1t put on one): the
139 /// credential belongs to the workspace, and acts on behalf of g1t
140 /// (`system::ID`), so what it does is g1t's, and the pull request g1t
141 /// opened, and its working copy, are its own.
142 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143 pub system: bool,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API144}
145
146/// A person, by id and name.
147#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]
148pub struct Principal {
149 pub id: String,
150 pub username: String,
151}
152
g1t is the stored author of what it opens; the person who asked is requested_by and keeps the author's rights153impl From<&User> for Principal {
154 fn from(user: &User) -> Self {
155 Principal {
156 id: user.id.clone(),
157 username: user.username.clone(),
158 }
159 }
160}
161
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API162/// Set on a [`User`] resolved from an agent's token: the composite
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent163/// identity, "g1t on behalf of syntaqx", and what it may do.
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API164#[derive(Clone, Debug, Serialize, Deserialize)]
165#[serde(rename_all = "camelCase")]
166pub struct Acting {
167 /// The token's id, as audit entries name it.
168 pub credential_id: String,
169 pub agent: String,
170 pub on_behalf_of: Principal,
171 pub scope: AgentScope,
172}
173
174impl Acting {
175 pub fn run(&self) -> Option<&RunBinding> {
176 self.scope.run.as_ref()
177 }
178}
179
180/// `create_run_credential`: a token for one sandbox run. It acts as
181/// `agent` on behalf of `on_behalf_of`, can do only what `kind` and `usage`
182/// allow in `repo`, and expires after `ttl_seconds`, which should be the
183/// run's timeout. Returns `CreatedAccessToken`.
184#[derive(Clone, Debug, Serialize, Deserialize)]
185#[serde(rename_all = "camelCase")]
186pub struct CreateRunCredentialArgs {
187 pub on_behalf_of: User,
188 pub repo: RepoPath,
189 pub kind: RunCredentialKind,
190 #[serde(rename = "use")]
191 pub usage: CredentialUse,
192 #[serde(default)]
193 pub number: Option<u32>,
194 #[serde(default)]
195 pub read: Vec<RepoPath>,
196 #[serde(default)]
197 pub push: Vec<GitGrant>,
198 pub ttl_seconds: u64,
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent199 /// Defaults to `g1t`.
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API200 #[serde(default)]
201 pub agent: Option<String>,
202}
203
204/// `bind_run_credentials`: ties tokens, named by the SHA-256 of their
205/// text in hex, to the agent run their sandbox recorded. Returns how many.
206#[derive(Clone, Debug, Serialize, Deserialize)]
207#[serde(rename_all = "camelCase")]
208pub struct BindRunCredentialsArgs {
209 pub token_hashes: Vec<String>,
210 pub run_id: String,
211}
212
213/// `revoke_run_credentials`: ends tokens when their sandbox stops, by hash
214/// or by run. Only run credentials are touched, never a token a person
215/// made. Returns how many.
216#[derive(Clone, Debug, Default, Serialize, Deserialize)]
217#[serde(rename_all = "camelCase")]
218pub struct RevokeRunCredentialsArgs {
219 #[serde(default)]
220 pub token_hashes: Vec<String>,
221 #[serde(default)]
222 pub run_id: Option<String>,
223}
224
225// --- Policy --------------------------------------------------------------
226
227/// Operations that only read.
228pub const READ_OPERATIONS: &[&str] = &[
229 "whoami",
Usage, Billing settings and prepaid AI credit; fixes from the UX audit230 "get_usage",
231 "get_budget",
232 "get_ai_credit",
233 "list_invoices",
234 "get_billing_details",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API235 "list_repos",
236 "get_repo",
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb97237 "list_projects",
238 "get_project",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look239 "list_deleted_repos",
240 "list_collaborators",
241 "get_collaborator_permission",
242 "list_repo_invitations",
243 "list_my_repo_invitations",
244 "list_outside_collaborators",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar245 "list_teams",
246 "get_team",
247 "list_team_members",
248 "list_child_teams",
249 "list_team_repos",
250 "list_user_teams",
251 "get_codeowners_errors",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API252 "get_repo_settings",
Fast pages, required checks on the branch, self-hosted runners, honest incidents253 "list_check_names",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API254 "get_merge_queue",
255 "recall",
256 "list_issues",
257 "get_issue",
258 "get_plan",
259 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar260 "list_issue_labels",
261 "list_milestones",
262 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API263 "list_pull_requests",
264 "get_pull_request",
265 "read_session",
266 "get_pull_request_changes",
267 "list_events",
268 "get_context",
269 "search_context",
270 "get_entity",
Search across all of g1t, Explore, and a command palette271 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API272 "list_workflows",
273 "list_workflow_runs",
274 "get_workflow_run",
275 "get_job_logs",
Merge branch 'worktree-agent-a3abfcce648e87dca'276 "get_pending_deployments",
277 "get_workflow_permissions",
278 "get_fork_pr_approval",
Merge checks: statuses and check runs on every commit279 "list_commit_statuses",
280 "get_combined_status",
281 "list_check_runs_for_ref",
282 "get_check_run",
283 "list_check_run_annotations",
284 "list_check_suites_for_ref",
285 "get_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API286 "list_integrations",
287 "get_model_routes",
288 "list_webhooks",
289 "list_webhook_deliveries",
290 "list_actions_secrets",
291 "list_actions_variables",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily292 "list_security_alerts",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar293 "list_secret_scanning_alerts",
294 "get_secret_scanning_alert",
295 "list_secret_scanning_locations",
296 "list_bypass_requests",
297 "list_custom_patterns",
298 "list_code_scanning_alerts",
299 "get_code_scanning_alert",
300 "list_code_scanning_analyses",
301 "get_sarif_upload",
302 "list_vulnerability_alerts",
303 "get_vulnerability_alert",
304 "get_dependency_graph",
305 "get_sbom",
306 "compare_dependencies",
307 "get_security_settings",
308 "get_workspace_security_settings",
309 "get_security_overview",
API: notifications over REST and MCP, with notifications scopes310 "list_notifications",
311 "get_notification_thread",
312 "get_thread_subscription",
313 "get_repo_subscription",
314 "list_watched_repos",
API: pinned projects over REST and MCP315 "list_pinned_projects",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API316];
317
318/// What no agent's token may ever do, whatever its scope says: workspaces,
319/// repositories' settings, members, tokens, billing, integrations,
320/// webhooks, secrets, workflows' controls, merging, and putting more agents
321/// to work.
322pub const NEVER: &[&str] = &[
Usage, Billing settings and prepaid AI credit; fixes from the UX audit323 // Billing is people's: agents never spend or change it.
324 "set_budget",
325 "buy_ai_credit",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API326 "create_workspace",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look327 "delete_workspace",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily328 "update_workspace",
Merge main (membership, two-factor, GitHub repo roles) into tokens329 // So is who belongs to a workspace and who owns it.
330 "list_members",
331 "update_member",
332 "remove_member",
333 "transfer_ownership",
334 "leave_workspace",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look335 "transfer_repo",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API336 "create_repo",
337 "update_repo",
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb97338 "update_project",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look339 "delete_repo",
340 "list_deleted_repos",
341 "restore_repo",
342 "purge_repo",
343 "rename_repo",
344 "archive_repo",
345 "unarchive_repo",
346 "set_repo_visibility",
347 "rename_branch",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API348 "update_repo_settings",
349 "merge_pull_request",
350 "assign_issue",
351 "plan_work",
352 "apply_plan",
353 "import_issue",
354 "list_integrations",
355 "connect_integration",
AI Gateway: OpenAI's format, open models, and your own providers356 "update_integration",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API357 "disconnect_integration",
358 "test_integration",
359 "get_model_routes",
360 "set_model_routes",
361 "list_webhooks",
362 "create_webhook",
363 "update_webhook",
364 "delete_webhook",
365 "ping_webhook",
366 "list_webhook_deliveries",
367 "redeliver_webhook",
368 "dispatch_workflow",
369 "cancel_workflow_run",
370 "rerun_workflow_run",
371 "update_workflow",
Merge branch 'worktree-agent-a3abfcce648e87dca'372 // Nor lets runs or deployments through, or changes what holds them.
373 "approve_workflow_run",
374 "review_pending_deployments",
375 "update_environment",
376 "delete_environment",
377 "set_workflow_permissions",
378 "set_fork_pr_approval",
Merge Actions: cross-repo workflows and actions, release and deployment triggers, step timeouts379 "set_actions_access",
Merge branch 'worktree-agent-a3abfcce648e87dca'380 "create_repository_dispatch",
381 "set_workspace_workflow_permissions",
Merge checks: statuses and check runs on every commit382 // An agent never reports checks on its own work, nor asks for them
383 // to run again: what checks say is the integrations' to say.
384 "create_commit_status",
385 "create_check_run",
386 "update_check_run",
387 "rerequest_check_run",
388 "rerequest_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API389 "list_actions_secrets",
390 "set_actions_secret",
391 "delete_actions_secret",
392 "list_actions_variables",
393 "set_actions_variable",
394 "delete_actions_variable",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look395 "list_collaborators",
396 "get_collaborator_permission",
397 "add_collaborator",
398 "update_collaborator",
399 "remove_collaborator",
400 "list_repo_invitations",
401 "revoke_repo_invitation",
402 "list_my_repo_invitations",
403 "accept_repo_invitation",
404 "decline_repo_invitation",
Merge workspace invitations: nobody joins a workspace without saying yes, people are found by username, your own invites can bring someone in, and nobody is left without a workspace (identity 0040)405 // Nor answers a workspace invitation: only the person it is for does.
406 "accept_invitation",
407 "decline_invitation",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look408 "set_base_permission",
409 "list_outside_collaborators",
Merge branch 'worktree-agent-a5a5de74d8863d554' into worktree-agent-a16631325aecf58ca410 // Deploy keys, which let a machine into a repository.
411 "list_deploy_keys",
412 "get_deploy_key",
413 "create_deploy_key",
414 "delete_deploy_key",
Merge branch 'mirroring' into artifacts-mode415 // Moving a repository to g1t for good, and a remote's token and
416 // levers, are a person's to decide.
417 "move_mirror_to_g1t",
418 "add_mirror_remote",
419 "update_mirror_remote",
420 "remove_mirror_remote",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar421 // Teams: who is in which, and what they reach, is for people.
422 "create_team",
423 "update_team",
424 "delete_team",
425 "set_team_member",
426 "remove_team_member",
427 "set_team_repo",
428 "remove_team_repo",
429 "set_team_review_assignment",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily430 // Dismissing a secret lets it through push protection.
431 "dismiss_security_alert",
432 "reopen_security_alert",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar433 // Nor any other decision about security: closing or reopening an
434 // alert, pushing past push protection or deciding who may, changing
435 // what is looked for or when checks fail, or putting more agents to
436 // work. An agent fixes what it finds in its own pull request.
437 "update_secret_scanning_alert",
438 "bypass_push_protection",
439 "review_bypass_request",
440 "create_custom_pattern",
441 "update_custom_pattern",
442 "delete_custom_pattern",
443 "update_code_scanning_alert",
444 "update_vulnerability_alert",
445 "fix_security_alert",
446 "update_security_settings",
447 "update_workspace_security_settings",
API: notifications over REST and MCP, with notifications scopes448 // A person's own inbox: g1t's agents act as g1t, which has none.
449 "list_notifications",
450 "get_notification_thread",
451 "mark_notifications_read",
452 "mark_thread_read",
453 "mark_thread_done",
454 "save_thread",
455 "snooze_thread",
456 "get_thread_subscription",
457 "set_thread_subscription",
458 "delete_thread_subscription",
459 "get_repo_subscription",
460 "set_repo_subscription",
461 "delete_repo_subscription",
462 "list_watched_repos",
API: pinned projects over REST and MCP463 // Pins are a person's own, as the inbox is.
464 "list_pinned_projects",
465 "pin_project",
466 "unpin_project",
467 "reorder_pinned_projects",
Merge packages: roles, Actions access, source label, soft delete, API468 // Deleting packages and deciding who may use them is for people: an
469 // agent publishes its repository's packages and never deletes them.
470 "update_package",
471 "link_package",
472 "unlink_package",
473 "set_package_access",
474 "remove_package_access",
475 "set_package_actions_access",
476 "remove_package_actions_access",
477 "delete_package",
478 "restore_package",
479 "delete_package_version",
480 "restore_package_version",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API481];
482
483/// Reading what an agent needs to know about its repository.
484const TOOLS_READ: &[&str] = &[
485 "get_repo",
486 "list_issues",
487 "get_issue",
488 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar489 "list_issue_labels",
490 "list_milestones",
491 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API492 "list_pull_requests",
493 "get_pull_request",
494 "get_pull_request_changes",
495 "read_session",
496 "get_merge_queue",
497 "list_events",
498 "recall",
499 "search_context",
500 "get_entity",
Search across all of g1t, Explore, and a command palette501 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API502 "list_workflows",
503 "list_workflow_runs",
504 "get_workflow_run",
505 "get_job_logs",
Merge branch 'worktree-agent-a3abfcce648e87dca'506 "get_pending_deployments",
507 "get_workflow_permissions",
508 "get_fork_pr_approval",
Merge checks: statuses and check runs on every commit509 "list_commit_statuses",
510 "get_combined_status",
511 "list_check_runs_for_ref",
512 "get_check_run",
513 "list_check_run_annotations",
514 "list_check_suites_for_ref",
515 "get_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API516];
517
518pub fn is_read(operation: &str) -> bool {
519 READ_OPERATIONS.contains(&operation)
520}
521
522/// The API and MCP operations a run of `kind` may use with a credential
523/// for `usage`. Git is separate: see [`decide_git`].
524pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
525 use RunCredentialKind as K;
526 let mut operations: Vec<&'static str> = Vec::new();
527 match usage {
528 CredentialUse::Runner => {
529 if kind.works_on_a_pull() {
530 operations.extend(["get_repo", "get_pull_request", "record_session"]);
531 }
532 if kind == K::Implement {
533 operations.push("mark_pull_request_ready");
534 }
535 }
536 CredentialUse::Tools => match kind {
537 K::Implement | K::Revise | K::Answer => {
538 operations.extend(TOOLS_READ.iter().copied());
539 operations.extend([
540 "create_issue",
541 "add_comment",
542 "take_messages",
543 "remember",
544 "message_agent",
545 "answer_message",
546 "get_context",
547 ]);
548 }
549 K::Review => {
550 operations.extend(TOOLS_READ.iter().copied());
551 operations.extend(["add_comment", "review_pull_request", "get_context"]);
552 }
553 K::Plan => {
554 operations.extend(TOOLS_READ.iter().copied());
555 operations.extend(["create_issue", "get_context"]);
556 }
557 K::Update => operations.extend(TOOLS_READ.iter().copied()),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily558 K::Checks | K::Queue | K::Mergecheck | K::Deploy | K::Bump => {}
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API559 },
560 }
561 operations
562}
563
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step564/// What a run's credential may do, in the scope vocabulary that access
565/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
566/// for a runner, git's. Its operations, its repository and its run still
567/// bound it more tightly than these scopes say.
568pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
569 use crate::scopes::{Scope, normalize, scope_for};
570 let mut scopes: Vec<Scope> = operations_for(kind, usage)
571 .into_iter()
572 .filter_map(scope_for)
573 .collect();
574 if usage == CredentialUse::Runner {
575 scopes.push(Scope::CodeRead);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily576 if matches!(
577 kind,
578 RunCredentialKind::Implement
579 | RunCredentialKind::Revise
580 | RunCredentialKind::Answer
581 | RunCredentialKind::Update
582 | RunCredentialKind::Bump
583 ) {
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step584 scopes.push(Scope::CodeWrite);
585 }
586 }
587 normalize(&mut scopes);
588 scopes
589}
590
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API591/// Operations that change a pull request, which a runner may do only to
592/// the pull request its run works on.
593const PULL_WRITES: &[&str] = &["record_session", "mark_pull_request_ready"];
594
595/// Whether something was allowed, and the rule that decided it.
596#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
597pub struct Decision {
598 pub allowed: bool,
599 /// A short, stable name: `run:implement/tools`, `never`,
600 /// `scope:repository` and so on. Shown in the audit log.
601 pub rule: String,
602 /// Why it was refused, for the caller.
603 #[serde(default, skip_serializing_if = "Option::is_none")]
604 pub reason: Option<String>,
605}
606
607impl Decision {
608 pub fn allow(rule: impl Into<String>) -> Self {
609 Decision {
610 allowed: true,
611 rule: rule.into(),
612 reason: None,
613 }
614 }
615
616 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
617 Decision {
618 allowed: false,
619 rule: rule.into(),
620 reason: Some(reason.into()),
621 }
622 }
623}
624
625fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
626 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
627}
628
629fn scope_rule(scope: &AgentScope) -> String {
630 match &scope.run {
631 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
632 None => "agent-token".to_owned(),
633 }
634}
635
636/// Whether `user`, resolved from an agent's token with `scope`, may use
637/// `operation`. `repo` is the repository the call names, if any, and
638/// `needs_repo` whether the operation is about one; `number` the issue or
639/// pull request it names.
640pub fn decide_operation(
641 user: &User,
642 scope: &AgentScope,
643 operation: &str,
644 repo: Option<&RepoPath>,
645 needs_repo: bool,
646 number: Option<u32>,
647) -> Decision {
648 let who = "A g1t agent's token";
649 if NEVER.contains(&operation) {
650 return Decision::deny(
651 "never",
652 format!(
653 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
654 ),
655 );
656 }
657 if !scope.operations.iter().any(|name| name == operation) {
658 return Decision::deny(
659 "scope:operation",
660 format!("{who} for this run cannot use {operation}."),
661 );
662 }
663 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
664 return Decision::deny(
665 "scope:repository",
666 format!(
667 "{who} works in {}/{} only.",
668 scope.repo.namespace, scope.repo.name
669 ),
670 );
671 }
672 // The intersection: the person it acts for must still be able to work
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look673 // in the repository's workspace, as a member or with a role on its
674 // repositories. What it may do in the repository itself is their
675 // role there, which services check (`access::can`).
676 if !crate::access::has_access_in(user, &scope.repo.namespace) {
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API677 return Decision::deny(
678 "on-behalf-of:membership",
679 format!(
680 "The person this agent works for is no longer a member of {}.",
681 scope.repo.namespace
682 ),
683 );
684 }
685 if let Some(run) = &scope.run
686 && run.usage == CredentialUse::Runner
687 && PULL_WRITES.contains(&operation)
688 && run.number.is_some()
689 && number != run.number
690 {
691 return Decision::deny(
692 "scope:pull",
693 format!(
694 "{who} can change pull request #{} only.",
695 run.number.unwrap_or_default()
696 ),
697 );
698 }
699 Decision::allow(scope_rule(scope))
700}
701
702/// Whether a run credential may clone or fetch (`write` false), or push to
703/// (`write` true), the repository at `repo`.
704pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
705 let Some(run) = scope
706 .run
707 .as_ref()
708 .filter(|run| run.usage == CredentialUse::Runner)
709 else {
710 return Decision::deny(
711 "git:not-a-run",
712 "A g1t agent's tools token cannot be used with git.",
713 );
714 };
715 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
716 if write {
717 return if pushable {
718 Decision::allow(format!("{}:push", scope_rule(scope)))
719 } else {
720 Decision::deny(
721 "git:push",
722 format!(
723 "A {} run cannot push to {}/{}.",
724 run.kind.as_str(),
725 repo.namespace,
726 repo.name
727 ),
728 )
729 };
730 }
731 let readable = pushable
732 || same_repo(&scope.repo, repo)
733 || run.read.iter().any(|path| same_repo(path, repo));
734 if readable {
735 Decision::allow(format!("{}:read", scope_rule(scope)))
736 } else {
737 Decision::deny(
738 "git:read",
739 format!(
740 "A {} run cannot read {}/{}.",
741 run.kind.as_str(),
742 repo.namespace,
743 repo.name
744 ),
745 )
746 }
747}
748
749/// Whether a push to `repo` is limited to certain branches, so that the
750/// refs it moves have to be read and checked with [`decide_refs`].
751pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
752 scope
753 .run
754 .iter()
755 .flat_map(|run| run.push.iter())
756 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
757}
758
759/// Whether a push to `repo` may move `refs` (full refs, such as
760/// `refs/heads/main`). Tags are never a run's to move.
761pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
762 let repo_decision = decide_git(scope, repo, true);
763 if !repo_decision.allowed {
764 return repo_decision;
765 }
766 let grants: Vec<&GitGrant> = scope
767 .run
768 .iter()
769 .flat_map(|run| run.push.iter())
770 .filter(|grant| same_repo(&grant.repo, repo))
771 .collect();
772 for git_ref in refs {
773 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
774 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
775 };
776 let allowed = grants
777 .iter()
778 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
779 if !allowed {
780 return Decision::deny(
781 "git:ref",
782 format!(
783 "A run cannot push to {branch} in {}/{}.",
784 repo.namespace, repo.name
785 ),
786 );
787 }
788 }
789 repo_decision
790}
791
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look792/// The most an agent may be on a repository, whoever it works for: it
793/// can push, merge and run, never change settings or who has access.
794pub const AGENT_CEILING: RepoRole = RepoRole::Write;
795
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API796/// The memberships an agent working for `person` has: the run's
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look797/// workspace, as a member, only if the person is in it now, with the
798/// person's role on its repositories (an owner's Admin included) cut down
799/// to [`AGENT_CEILING`].
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API800pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
801 let namespace = namespace.to_lowercase();
802 person
803 .iter()
804 .filter(|membership| membership.slug == namespace)
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look805 .map(|membership| {
806 let base = match membership.role {
807 Role::Owner => BasePermission::Admin,
808 Role::Member => membership.base_permission.unwrap_or_default(),
809 };
810 Membership {
811 role: Role::Member,
812 base_permission: Some(match base {
813 BasePermission::Admin => BasePermission::Write,
814 base => base,
815 }),
Merge main (membership, two-factor, GitHub repo roles) into tokens816 // Billing and security manager are the person's, never
817 // their agent's.
818 org_roles: Vec::new(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look819 ..membership.clone()
820 }
821 })
822 .collect()
823}
824
825/// The repository grants an agent working for `person` has: those in the
826/// run's workspace, each cut down to [`AGENT_CEILING`].
827pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
828 let namespace = namespace.to_lowercase();
829 person
830 .iter()
831 .filter(|grant| grant.workspace == namespace)
832 .map(|grant| RepoGrant {
833 role: grant.role.min(AGENT_CEILING),
834 ..grant.clone()
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API835 })
836 .collect()
837}
838
839/// Who a runner's credential acts as downstream: the person, with only the
840/// agent's (already intersected) memberships. `None` for anything else.
841pub fn as_person(user: &User) -> Option<User> {
842 let acting = user.acting.as_ref()?;
843 if user.kind != PrincipalKind::Agent {
844 return None;
845 }
846 let run = acting.run()?;
847 if run.usage != CredentialUse::Runner {
848 return None;
849 }
850 Some(User {
851 id: acting.on_behalf_of.id.clone(),
852 username: acting.on_behalf_of.username.clone(),
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers853 display_username: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API854 kind: PrincipalKind::User,
855 verified: user.verified,
856 workspaces: user.workspaces.clone(),
857 avatar: None,
858 acting: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look859 grants: user.grants.clone(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step860 token: None,
Merge main (membership, two-factor, GitHub repo roles) into tokens861 held: Vec::new(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API862 })
863}
864
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent865/// How an actor is described: "g1t on behalf of syntaqx".
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API866pub fn describe(user: &User) -> String {
867 match &user.acting {
868 Some(acting) => format!(
869 "{} on behalf of {}",
870 acting.agent, acting.on_behalf_of.username
871 ),
872 None => user.username.clone(),
873 }
874}
875
876#[cfg(test)]
877mod tests {
878 use super::*;
879
880 #[test]
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step881 fn a_run_s_scopes_are_never_admin() {
882 for kind in RunCredentialKind::ALL {
883 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
884 let scopes = run_scopes(kind, usage);
885 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
886 }
887 }
888 let review = run_scopes(RunCredentialKind::Review, CredentialUse::Tools);
889 assert!(review.contains(&crate::scopes::Scope::PullRequestsWrite));
890 assert!(!review.contains(&crate::scopes::Scope::CodeWrite));
891 }
892
893 #[test]
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API894 fn agents_can_search_the_context_hub() {
895 for kind in [RunCredentialKind::Implement, RunCredentialKind::Review, RunCredentialKind::Plan] {
896 let tools = operations_for(kind, CredentialUse::Tools);
897 assert!(tools.contains(&"search_context") && tools.contains(&"get_entity"));
898 }
899 assert!(is_read("search_context") && is_read("get_entity"));
900 }
901
Search across all of g1t, Explore, and a command palette902 #[test]
903 fn agents_can_search_all_of_g1t() {
904 // Site-wide search only reads: every run that reads its repository
905 // may use it, and nothing that never reads gets it.
906 assert!(is_read("search"));
907 assert!(!NEVER.contains(&"search"));
908 for kind in [
909 RunCredentialKind::Implement,
910 RunCredentialKind::Revise,
911 RunCredentialKind::Answer,
912 RunCredentialKind::Review,
913 RunCredentialKind::Plan,
914 RunCredentialKind::Update,
915 ] {
916 let tools = operations_for(kind, CredentialUse::Tools);
917 assert!(tools.contains(&"search"), "{kind:?} should search");
918 // The context hub's search stays its own tool beside it.
919 assert!(tools.contains(&"search_context"), "{kind:?} keeps search_context");
920 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily921 for kind in [RunCredentialKind::Checks, RunCredentialKind::Queue, RunCredentialKind::Mergecheck, RunCredentialKind::Deploy, RunCredentialKind::Bump] {
Search across all of g1t, Explore, and a command palette922 assert!(!operations_for(kind, CredentialUse::Tools).contains(&"search"));
923 }
924 assert!(!operations_for(RunCredentialKind::Implement, CredentialUse::Runner).contains(&"search"));
925 }
926
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API927 fn path(namespace: &str, name: &str) -> RepoPath {
928 RepoPath {
929 namespace: namespace.to_owned(),
930 name: name.to_owned(),
931 }
932 }
933
934 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
935 AgentScope {
936 repo: path("acme", "rocket"),
937 operations: operations_for(kind, usage)
938 .into_iter()
939 .map(str::to_owned)
940 .collect(),
941 run: Some(RunBinding {
942 kind,
943 usage,
944 run_id: Some("run_1".to_owned()),
945 number: Some(7),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent946 agent: "g1t".to_owned(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily947 system: false,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API948 read: vec![path("acme", "rocket")],
949 push: match kind {
950 RunCredentialKind::Implement
951 | RunCredentialKind::Revise
952 | RunCredentialKind::Answer => vec![GitGrant {
953 repo: path("pulls", "pul_7"),
954 branch: None,
955 }],
956 RunCredentialKind::Update => vec![GitGrant {
957 repo: path("acme", "rocket"),
958 branch: Some("fix-login".to_owned()),
959 }],
960 _ => vec![],
961 },
962 }),
963 }
964 }
965
966 fn agent(member_of: &[&str], scope: AgentScope) -> User {
967 User {
968 id: "usr_g1t_agent".to_owned(),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent969 username: "g1t".to_owned(),
One kind of access token; presence and status; usernames keep their case; the tour is a miniature of the real app; icons for password managers970 display_username: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API971 kind: PrincipalKind::Agent,
972 verified: true,
973 workspaces: member_of
974 .iter()
975 .map(|slug| Membership::member(*slug))
976 .collect(),
977 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look978 grants: Vec::new(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step979 token: None,
Merge main (membership, two-factor, GitHub repo roles) into tokens980 held: Vec::new(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API981 acting: Some(Box::new(Acting {
982 credential_id: "tok_1".to_owned(),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent983 agent: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API984 on_behalf_of: Principal {
985 id: "usr_1".to_owned(),
986 username: "syntaqx".to_owned(),
987 },
988 scope,
989 })),
990 }
991 }
992
993 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
994 let scope = scope(kind, usage);
995 let user = agent(&["acme"], scope.clone());
996 decide_operation(
997 &user,
998 &scope,
999 operation,
1000 Some(&path("acme", "rocket")),
1001 true,
1002 Some(7),
1003 )
1004 }
1005
1006 use CredentialUse::{Runner, Tools};
1007 use RunCredentialKind as K;
1008
1009 /// Which operations each kind of run may use through its tools: the
1010 /// allowed and denied matrix.
1011 #[test]
1012 fn tools_matrix() {
1013 let cases: [(&str, [bool; 6]); 12] = [
1014 // implement revise answer review plan checks
1015 ("get_issue", [true, true, true, true, true, false]),
1016 ("create_issue", [true, true, true, false, true, false]),
1017 ("add_comment", [true, true, true, true, false, false]),
1018 (
1019 "review_pull_request",
1020 [false, false, false, true, false, false],
1021 ),
1022 ("remember", [true, true, true, false, false, false]),
1023 ("take_messages", [true, true, true, false, false, false]),
1024 ("record_session", [false, false, false, false, false, false]),
1025 (
1026 "merge_pull_request",
1027 [false, false, false, false, false, false],
1028 ),
1029 (
1030 "update_repo_settings",
1031 [false, false, false, false, false, false],
1032 ),
1033 ("create_webhook", [false, false, false, false, false, false]),
1034 (
1035 "set_actions_secret",
1036 [false, false, false, false, false, false],
1037 ),
1038 ("assign_issue", [false, false, false, false, false, false]),
1039 ];
1040 let kinds = [
1041 K::Implement,
1042 K::Revise,
1043 K::Answer,
1044 K::Review,
1045 K::Plan,
1046 K::Checks,
1047 ];
1048 for (operation, expected) in cases {
1049 for (kind, allowed) in kinds.into_iter().zip(expected) {
1050 assert_eq!(
1051 op(kind, Tools, operation).allowed,
1052 allowed,
1053 "{operation} by a {} run's tools",
1054 kind.as_str()
1055 );
1056 }
1057 }
1058 }
1059
1060 #[test]
1061 fn runner_matrix() {
1062 assert!(op(K::Implement, Runner, "record_session").allowed);
1063 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
1064 assert!(op(K::Revise, Runner, "record_session").allowed);
1065 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
1066 assert!(!op(K::Implement, Runner, "create_issue").allowed);
1067 assert!(!op(K::Review, Runner, "record_session").allowed);
1068 assert!(!op(K::Checks, Runner, "get_issue").allowed);
1069 }
1070
1071 #[test]
1072 fn settings_billing_tokens_and_members_are_never_reachable() {
1073 for kind in RunCredentialKind::ALL {
1074 for usage in [Runner, Tools] {
1075 for operation in NEVER.iter().copied() {
1076 let decision = op(kind, usage, operation);
1077 assert!(!decision.allowed);
1078 assert_eq!(decision.rule, "never");
1079 }
1080 }
1081 }
1082 // Even a scope that lists one is refused.
1083 let mut wide = scope(K::Implement, Tools);
1084 wide.operations.push("merge_pull_request".to_owned());
1085 let user = agent(&["acme"], wide.clone());
1086 let decision = decide_operation(
1087 &user,
1088 &wide,
1089 "merge_pull_request",
1090 Some(&path("acme", "rocket")),
1091 true,
1092 Some(7),
1093 );
1094 assert_eq!(decision.rule, "never");
1095 }
1096
1097 #[test]
1098 fn another_repository_is_refused() {
1099 let scope = scope(K::Implement, Tools);
1100 let user = agent(&["acme"], scope.clone());
1101 let decision = decide_operation(
1102 &user,
1103 &scope,
1104 "create_issue",
1105 Some(&path("acme", "other")),
1106 true,
1107 None,
1108 );
1109 assert!(!decision.allowed);
1110 assert_eq!(decision.rule, "scope:repository");
1111 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1112 assert_eq!(decision.rule, "scope:repository");
1113 // The repository's name is matched without regard to case.
1114 let decision = decide_operation(
1115 &user,
1116 &scope,
1117 "create_issue",
1118 Some(&path("Acme", "Rocket")),
1119 true,
1120 None,
1121 );
1122 assert!(decision.allowed);
1123 assert_eq!(decision.rule, "run:implement/tools");
1124 }
1125
1126 #[test]
1127 fn the_permission_is_the_intersection_with_the_person() {
1128 let scope = scope(K::Implement, Tools);
1129 // The person left the workspace: their agent can do nothing there.
1130 let user = agent(&[], scope.clone());
1131 let decision = decide_operation(
1132 &user,
1133 &scope,
1134 "get_issue",
1135 Some(&path("acme", "rocket")),
1136 true,
1137 Some(1),
1138 );
1139 assert!(!decision.allowed);
1140 assert_eq!(decision.rule, "on-behalf-of:membership");
1141 // And an owner's agent is only ever a member.
1142 let owner = vec![
1143 Membership {
1144 slug: "acme".to_owned(),
1145 role: Role::Owner,
1146 name: None,
1147 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1148 base_permission: Some(BasePermission::None),
Merge branch 'worktree-agent-ad7c6d88d93adc817'1149 team_creation: None,
Merge main (membership, two-factor, GitHub repo roles) into tokens1150 org_roles: vec![crate::OrgRole::SecurityManager],
1151 privileges: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1152 },
1153 Membership::member("elsewhere"),
1154 ];
1155 let memberships = intersect(&owner, "Acme");
1156 assert_eq!(memberships.len(), 1);
1157 assert_eq!(memberships[0].slug, "acme");
1158 assert_eq!(memberships[0].role, Role::Member);
Merge main (membership, two-factor, GitHub repo roles) into tokens1159 assert!(memberships[0].org_roles.is_empty());
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1160 assert!(intersect(&owner, "nowhere").is_empty());
1161 }
1162
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1163 /// An agent gets at most the person's role on the repository, and
1164 /// never more than Write; nothing outside the run's workspace.
1165 #[test]
1166 fn an_agent_has_at_most_its_persons_role() {
1167 use crate::access::{Capability, RepoRef, can, permission};
1168 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1169 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1170 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1171 let tools = scope(K::Implement, Tools);
1172 let scope = scope(K::Implement, Runner);
1173 // An owner's agent: Write, never Admin.
1174 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1175 let mut agent_user = agent(&[], scope.clone());
1176 agent_user.workspaces = intersect(&owner, "acme");
1177 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1178 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1179 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1180 // A member whose workspace gives Read: Read, so it cannot push.
1181 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1182 agent_user.workspaces = intersect(&reader, "acme");
1183 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1184 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1185 // An outside collaborator with Maintain on one repository: Write
1186 // there, nothing elsewhere, and the run is allowed.
1187 let grants = [
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1188 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1189 RepoGrant { repo_id: "rep_3".into(), workspace: "globex".into(), role: RepoRole::Admin, team: None },
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1190 ];
1191 agent_user.workspaces = intersect(&[], "acme");
1192 agent_user.grants = intersect_grants(&grants, "Acme");
1193 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1194 assert_eq!(permission(Some(&agent_user), other), None);
1195 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1196 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1197 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1198 // The person, downstream of a runner's credential, carries the same.
1199 let person = as_person(&agent_user).expect("a runner acts as the person");
1200 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1201 }
1202
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1203 #[test]
1204 fn a_runner_changes_only_its_own_pull_request() {
1205 let scope = scope(K::Implement, Runner);
1206 let user = agent(&["acme"], scope.clone());
1207 let repo = path("acme", "rocket");
1208 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1209 assert!(!other.allowed);
1210 assert_eq!(other.rule, "scope:pull");
1211 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1212 assert!(own.allowed);
1213 // Reading another is fine.
1214 assert!(
1215 decide_operation(
1216 &user,
1217 &scope,
1218 "get_pull_request",
1219 Some(&repo),
1220 true,
1221 Some(8)
1222 )
1223 .allowed
1224 );
1225 }
1226
1227 #[test]
1228 fn git_matrix() {
1229 let fork = path("pulls", "pul_7");
1230 let upstream = path("acme", "rocket");
1231 let elsewhere = path("acme", "billing");
1232 let implement = scope(K::Implement, Runner);
1233 assert!(decide_git(&implement, &fork, true).allowed);
1234 assert!(decide_git(&implement, &fork, false).allowed);
1235 assert!(decide_git(&implement, &upstream, false).allowed);
1236 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1237 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1238 let review = scope(K::Review, Runner);
1239 assert!(decide_git(&review, &upstream, false).allowed);
1240 assert!(!decide_git(&review, &upstream, true).allowed);
1241 assert!(!decide_git(&review, &fork, true).allowed);
1242 // A tools token made before run credentials never reaches git.
1243 let old = AgentScope {
1244 repo: upstream.clone(),
1245 operations: vec!["get_issue".to_owned()],
1246 run: None,
1247 };
1248 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1249 // Nor does an agent's tools token.
1250 assert_eq!(
1251 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1252 "git:not-a-run"
1253 );
1254 }
1255
1256 #[test]
1257 fn a_push_moves_only_granted_branches() {
1258 let update = scope(K::Update, Runner);
1259 let repo = path("acme", "rocket");
1260 let refs = |names: &[&str]| {
1261 names
1262 .iter()
1263 .map(|name| (*name).to_owned())
1264 .collect::<Vec<_>>()
1265 };
1266 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1267 assert_eq!(
1268 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1269 "git:ref"
1270 );
1271 assert_eq!(
1272 decide_refs(
1273 &update,
1274 &repo,
1275 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1276 )
1277 .rule,
1278 "git:ref"
1279 );
1280 let implement = scope(K::Implement, Runner);
1281 assert!(
1282 decide_refs(
1283 &implement,
1284 &path("pulls", "pul_7"),
1285 &refs(&["refs/heads/main"])
1286 )
1287 .allowed
1288 );
1289 }
1290
1291 #[test]
1292 fn a_runner_acts_downstream_as_the_person() {
1293 let user = agent(&["acme"], scope(K::Implement, Runner));
1294 let person = as_person(&user).unwrap();
1295 assert_eq!(person.id, "usr_1");
1296 assert_eq!(person.username, "syntaqx");
1297 assert_eq!(person.kind, PrincipalKind::User);
1298 assert!(person.is_member("acme"));
1299 assert!(person.acting.is_none());
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent1300 assert_eq!(describe(&user), "g1t on behalf of syntaqx");
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1301 // The tools act as the agent.
1302 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1303 }
1304
1305 #[test]
1306 fn scopes_without_a_run_still_parse() {
1307 let old: AgentScope = serde_json::from_str(
1308 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1309 )
1310 .unwrap();
1311 assert!(old.run.is_none());
1312 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1313 assert!(written.contains(r#""use":"tools""#));
1314 assert!(written.contains(r#""kind":"review""#));
1315 let back: AgentScope = serde_json::from_str(&written).unwrap();
1316 assert_eq!(back.run.unwrap().kind, K::Review);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1317 // Only g1t's own runs say so; every other reads as not.
1318 assert!(!written.contains("system"));
1319 assert!(!back_run(&written).system);
1320 let mut own = scope(K::Bump, Runner);
1321 own.run.as_mut().unwrap().system = true;
1322 let written = serde_json::to_string(&own).unwrap();
1323 assert!(written.contains(r#""system":true"#));
1324 assert!(back_run(&written).system);
1325 }
1326
1327 fn back_run(written: &str) -> RunBinding {
1328 serde_json::from_str::<AgentScope>(written).unwrap().run.unwrap()
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1329 }
1330}

This file's history is long; its oldest lines are credited to the oldest commit read.