Skip to content
1,305 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",
379 "create_repository_dispatch",
380 "set_workspace_workflow_permissions",
Merge checks: statuses and check runs on every commit381 // An agent never reports checks on its own work, nor asks for them
382 // to run again: what checks say is the integrations' to say.
383 "create_commit_status",
384 "create_check_run",
385 "update_check_run",
386 "rerequest_check_run",
387 "rerequest_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API388 "list_actions_secrets",
389 "set_actions_secret",
390 "delete_actions_secret",
391 "list_actions_variables",
392 "set_actions_variable",
393 "delete_actions_variable",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look394 "list_collaborators",
395 "get_collaborator_permission",
396 "add_collaborator",
397 "update_collaborator",
398 "remove_collaborator",
399 "list_repo_invitations",
400 "revoke_repo_invitation",
401 "list_my_repo_invitations",
402 "accept_repo_invitation",
403 "decline_repo_invitation",
404 "set_base_permission",
405 "list_outside_collaborators",
Merge branch 'worktree-agent-a5a5de74d8863d554' into worktree-agent-a16631325aecf58ca406 // Deploy keys, which let a machine into a repository.
407 "list_deploy_keys",
408 "get_deploy_key",
409 "create_deploy_key",
410 "delete_deploy_key",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar411 // Teams: who is in which, and what they reach, is for people.
412 "create_team",
413 "update_team",
414 "delete_team",
415 "set_team_member",
416 "remove_team_member",
417 "set_team_repo",
418 "remove_team_repo",
419 "set_team_review_assignment",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily420 // Dismissing a secret lets it through push protection.
421 "dismiss_security_alert",
422 "reopen_security_alert",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar423 // Nor any other decision about security: closing or reopening an
424 // alert, pushing past push protection or deciding who may, changing
425 // what is looked for or when checks fail, or putting more agents to
426 // work. An agent fixes what it finds in its own pull request.
427 "update_secret_scanning_alert",
428 "bypass_push_protection",
429 "review_bypass_request",
430 "create_custom_pattern",
431 "update_custom_pattern",
432 "delete_custom_pattern",
433 "update_code_scanning_alert",
434 "update_vulnerability_alert",
435 "fix_security_alert",
436 "update_security_settings",
437 "update_workspace_security_settings",
API: notifications over REST and MCP, with notifications scopes438 // A person's own inbox: g1t's agents act as g1t, which has none.
439 "list_notifications",
440 "get_notification_thread",
441 "mark_notifications_read",
442 "mark_thread_read",
443 "mark_thread_done",
444 "save_thread",
445 "snooze_thread",
446 "get_thread_subscription",
447 "set_thread_subscription",
448 "delete_thread_subscription",
449 "get_repo_subscription",
450 "set_repo_subscription",
451 "delete_repo_subscription",
452 "list_watched_repos",
API: pinned projects over REST and MCP453 // Pins are a person's own, as the inbox is.
454 "list_pinned_projects",
455 "pin_project",
456 "unpin_project",
457 "reorder_pinned_projects",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API458];
459
460/// Reading what an agent needs to know about its repository.
461const TOOLS_READ: &[&str] = &[
462 "get_repo",
463 "list_issues",
464 "get_issue",
465 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar466 "list_issue_labels",
467 "list_milestones",
468 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API469 "list_pull_requests",
470 "get_pull_request",
471 "get_pull_request_changes",
472 "read_session",
473 "get_merge_queue",
474 "list_events",
475 "recall",
476 "search_context",
477 "get_entity",
Search across all of g1t, Explore, and a command palette478 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API479 "list_workflows",
480 "list_workflow_runs",
481 "get_workflow_run",
482 "get_job_logs",
Merge branch 'worktree-agent-a3abfcce648e87dca'483 "get_pending_deployments",
484 "get_workflow_permissions",
485 "get_fork_pr_approval",
Merge checks: statuses and check runs on every commit486 "list_commit_statuses",
487 "get_combined_status",
488 "list_check_runs_for_ref",
489 "get_check_run",
490 "list_check_run_annotations",
491 "list_check_suites_for_ref",
492 "get_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API493];
494
495pub fn is_read(operation: &str) -> bool {
496 READ_OPERATIONS.contains(&operation)
497}
498
499/// The API and MCP operations a run of `kind` may use with a credential
500/// for `usage`. Git is separate: see [`decide_git`].
501pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
502 use RunCredentialKind as K;
503 let mut operations: Vec<&'static str> = Vec::new();
504 match usage {
505 CredentialUse::Runner => {
506 if kind.works_on_a_pull() {
507 operations.extend(["get_repo", "get_pull_request", "record_session"]);
508 }
509 if kind == K::Implement {
510 operations.push("mark_pull_request_ready");
511 }
512 }
513 CredentialUse::Tools => match kind {
514 K::Implement | K::Revise | K::Answer => {
515 operations.extend(TOOLS_READ.iter().copied());
516 operations.extend([
517 "create_issue",
518 "add_comment",
519 "take_messages",
520 "remember",
521 "message_agent",
522 "answer_message",
523 "get_context",
524 ]);
525 }
526 K::Review => {
527 operations.extend(TOOLS_READ.iter().copied());
528 operations.extend(["add_comment", "review_pull_request", "get_context"]);
529 }
530 K::Plan => {
531 operations.extend(TOOLS_READ.iter().copied());
532 operations.extend(["create_issue", "get_context"]);
533 }
534 K::Update => operations.extend(TOOLS_READ.iter().copied()),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily535 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 API536 },
537 }
538 operations
539}
540
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step541/// What a run's credential may do, in the scope vocabulary that access
542/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
543/// for a runner, git's. Its operations, its repository and its run still
544/// bound it more tightly than these scopes say.
545pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
546 use crate::scopes::{Scope, normalize, scope_for};
547 let mut scopes: Vec<Scope> = operations_for(kind, usage)
548 .into_iter()
549 .filter_map(scope_for)
550 .collect();
551 if usage == CredentialUse::Runner {
552 scopes.push(Scope::CodeRead);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily553 if matches!(
554 kind,
555 RunCredentialKind::Implement
556 | RunCredentialKind::Revise
557 | RunCredentialKind::Answer
558 | RunCredentialKind::Update
559 | RunCredentialKind::Bump
560 ) {
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step561 scopes.push(Scope::CodeWrite);
562 }
563 }
564 normalize(&mut scopes);
565 scopes
566}
567
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API568/// Operations that change a pull request, which a runner may do only to
569/// the pull request its run works on.
570const PULL_WRITES: &[&str] = &["record_session", "mark_pull_request_ready"];
571
572/// Whether something was allowed, and the rule that decided it.
573#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
574pub struct Decision {
575 pub allowed: bool,
576 /// A short, stable name: `run:implement/tools`, `never`,
577 /// `scope:repository` and so on. Shown in the audit log.
578 pub rule: String,
579 /// Why it was refused, for the caller.
580 #[serde(default, skip_serializing_if = "Option::is_none")]
581 pub reason: Option<String>,
582}
583
584impl Decision {
585 pub fn allow(rule: impl Into<String>) -> Self {
586 Decision {
587 allowed: true,
588 rule: rule.into(),
589 reason: None,
590 }
591 }
592
593 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
594 Decision {
595 allowed: false,
596 rule: rule.into(),
597 reason: Some(reason.into()),
598 }
599 }
600}
601
602fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
603 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
604}
605
606fn scope_rule(scope: &AgentScope) -> String {
607 match &scope.run {
608 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
609 None => "agent-token".to_owned(),
610 }
611}
612
613/// Whether `user`, resolved from an agent's token with `scope`, may use
614/// `operation`. `repo` is the repository the call names, if any, and
615/// `needs_repo` whether the operation is about one; `number` the issue or
616/// pull request it names.
617pub fn decide_operation(
618 user: &User,
619 scope: &AgentScope,
620 operation: &str,
621 repo: Option<&RepoPath>,
622 needs_repo: bool,
623 number: Option<u32>,
624) -> Decision {
625 let who = "A g1t agent's token";
626 if NEVER.contains(&operation) {
627 return Decision::deny(
628 "never",
629 format!(
630 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
631 ),
632 );
633 }
634 if !scope.operations.iter().any(|name| name == operation) {
635 return Decision::deny(
636 "scope:operation",
637 format!("{who} for this run cannot use {operation}."),
638 );
639 }
640 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
641 return Decision::deny(
642 "scope:repository",
643 format!(
644 "{who} works in {}/{} only.",
645 scope.repo.namespace, scope.repo.name
646 ),
647 );
648 }
649 // 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 look650 // in the repository's workspace, as a member or with a role on its
651 // repositories. What it may do in the repository itself is their
652 // role there, which services check (`access::can`).
653 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 API654 return Decision::deny(
655 "on-behalf-of:membership",
656 format!(
657 "The person this agent works for is no longer a member of {}.",
658 scope.repo.namespace
659 ),
660 );
661 }
662 if let Some(run) = &scope.run
663 && run.usage == CredentialUse::Runner
664 && PULL_WRITES.contains(&operation)
665 && run.number.is_some()
666 && number != run.number
667 {
668 return Decision::deny(
669 "scope:pull",
670 format!(
671 "{who} can change pull request #{} only.",
672 run.number.unwrap_or_default()
673 ),
674 );
675 }
676 Decision::allow(scope_rule(scope))
677}
678
679/// Whether a run credential may clone or fetch (`write` false), or push to
680/// (`write` true), the repository at `repo`.
681pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
682 let Some(run) = scope
683 .run
684 .as_ref()
685 .filter(|run| run.usage == CredentialUse::Runner)
686 else {
687 return Decision::deny(
688 "git:not-a-run",
689 "A g1t agent's tools token cannot be used with git.",
690 );
691 };
692 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
693 if write {
694 return if pushable {
695 Decision::allow(format!("{}:push", scope_rule(scope)))
696 } else {
697 Decision::deny(
698 "git:push",
699 format!(
700 "A {} run cannot push to {}/{}.",
701 run.kind.as_str(),
702 repo.namespace,
703 repo.name
704 ),
705 )
706 };
707 }
708 let readable = pushable
709 || same_repo(&scope.repo, repo)
710 || run.read.iter().any(|path| same_repo(path, repo));
711 if readable {
712 Decision::allow(format!("{}:read", scope_rule(scope)))
713 } else {
714 Decision::deny(
715 "git:read",
716 format!(
717 "A {} run cannot read {}/{}.",
718 run.kind.as_str(),
719 repo.namespace,
720 repo.name
721 ),
722 )
723 }
724}
725
726/// Whether a push to `repo` is limited to certain branches, so that the
727/// refs it moves have to be read and checked with [`decide_refs`].
728pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
729 scope
730 .run
731 .iter()
732 .flat_map(|run| run.push.iter())
733 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
734}
735
736/// Whether a push to `repo` may move `refs` (full refs, such as
737/// `refs/heads/main`). Tags are never a run's to move.
738pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
739 let repo_decision = decide_git(scope, repo, true);
740 if !repo_decision.allowed {
741 return repo_decision;
742 }
743 let grants: Vec<&GitGrant> = scope
744 .run
745 .iter()
746 .flat_map(|run| run.push.iter())
747 .filter(|grant| same_repo(&grant.repo, repo))
748 .collect();
749 for git_ref in refs {
750 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
751 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
752 };
753 let allowed = grants
754 .iter()
755 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
756 if !allowed {
757 return Decision::deny(
758 "git:ref",
759 format!(
760 "A run cannot push to {branch} in {}/{}.",
761 repo.namespace, repo.name
762 ),
763 );
764 }
765 }
766 repo_decision
767}
768
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look769/// The most an agent may be on a repository, whoever it works for: it
770/// can push, merge and run, never change settings or who has access.
771pub const AGENT_CEILING: RepoRole = RepoRole::Write;
772
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API773/// 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 look774/// workspace, as a member, only if the person is in it now, with the
775/// person's role on its repositories (an owner's Admin included) cut down
776/// to [`AGENT_CEILING`].
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API777pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
778 let namespace = namespace.to_lowercase();
779 person
780 .iter()
781 .filter(|membership| membership.slug == namespace)
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look782 .map(|membership| {
783 let base = match membership.role {
784 Role::Owner => BasePermission::Admin,
785 Role::Member => membership.base_permission.unwrap_or_default(),
786 };
787 Membership {
788 role: Role::Member,
789 base_permission: Some(match base {
790 BasePermission::Admin => BasePermission::Write,
791 base => base,
792 }),
Merge main (membership, two-factor, GitHub repo roles) into tokens793 // Billing and security manager are the person's, never
794 // their agent's.
795 org_roles: Vec::new(),
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look796 ..membership.clone()
797 }
798 })
799 .collect()
800}
801
802/// The repository grants an agent working for `person` has: those in the
803/// run's workspace, each cut down to [`AGENT_CEILING`].
804pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
805 let namespace = namespace.to_lowercase();
806 person
807 .iter()
808 .filter(|grant| grant.workspace == namespace)
809 .map(|grant| RepoGrant {
810 role: grant.role.min(AGENT_CEILING),
811 ..grant.clone()
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API812 })
813 .collect()
814}
815
816/// Who a runner's credential acts as downstream: the person, with only the
817/// agent's (already intersected) memberships. `None` for anything else.
818pub fn as_person(user: &User) -> Option<User> {
819 let acting = user.acting.as_ref()?;
820 if user.kind != PrincipalKind::Agent {
821 return None;
822 }
823 let run = acting.run()?;
824 if run.usage != CredentialUse::Runner {
825 return None;
826 }
827 Some(User {
828 id: acting.on_behalf_of.id.clone(),
829 username: acting.on_behalf_of.username.clone(),
830 kind: PrincipalKind::User,
831 verified: user.verified,
832 workspaces: user.workspaces.clone(),
833 avatar: None,
834 acting: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look835 grants: user.grants.clone(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step836 token: None,
Merge main (membership, two-factor, GitHub repo roles) into tokens837 held: Vec::new(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API838 })
839}
840
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent841/// 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 API842pub fn describe(user: &User) -> String {
843 match &user.acting {
844 Some(acting) => format!(
845 "{} on behalf of {}",
846 acting.agent, acting.on_behalf_of.username
847 ),
848 None => user.username.clone(),
849 }
850}
851
852#[cfg(test)]
853mod tests {
854 use super::*;
855
856 #[test]
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step857 fn a_run_s_scopes_are_never_admin() {
858 for kind in RunCredentialKind::ALL {
859 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
860 let scopes = run_scopes(kind, usage);
861 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
862 }
863 }
864 let review = run_scopes(RunCredentialKind::Review, CredentialUse::Tools);
865 assert!(review.contains(&crate::scopes::Scope::PullRequestsWrite));
866 assert!(!review.contains(&crate::scopes::Scope::CodeWrite));
867 }
868
869 #[test]
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API870 fn agents_can_search_the_context_hub() {
871 for kind in [RunCredentialKind::Implement, RunCredentialKind::Review, RunCredentialKind::Plan] {
872 let tools = operations_for(kind, CredentialUse::Tools);
873 assert!(tools.contains(&"search_context") && tools.contains(&"get_entity"));
874 }
875 assert!(is_read("search_context") && is_read("get_entity"));
876 }
877
Search across all of g1t, Explore, and a command palette878 #[test]
879 fn agents_can_search_all_of_g1t() {
880 // Site-wide search only reads: every run that reads its repository
881 // may use it, and nothing that never reads gets it.
882 assert!(is_read("search"));
883 assert!(!NEVER.contains(&"search"));
884 for kind in [
885 RunCredentialKind::Implement,
886 RunCredentialKind::Revise,
887 RunCredentialKind::Answer,
888 RunCredentialKind::Review,
889 RunCredentialKind::Plan,
890 RunCredentialKind::Update,
891 ] {
892 let tools = operations_for(kind, CredentialUse::Tools);
893 assert!(tools.contains(&"search"), "{kind:?} should search");
894 // The context hub's search stays its own tool beside it.
895 assert!(tools.contains(&"search_context"), "{kind:?} keeps search_context");
896 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily897 for kind in [RunCredentialKind::Checks, RunCredentialKind::Queue, RunCredentialKind::Mergecheck, RunCredentialKind::Deploy, RunCredentialKind::Bump] {
Search across all of g1t, Explore, and a command palette898 assert!(!operations_for(kind, CredentialUse::Tools).contains(&"search"));
899 }
900 assert!(!operations_for(RunCredentialKind::Implement, CredentialUse::Runner).contains(&"search"));
901 }
902
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API903 fn path(namespace: &str, name: &str) -> RepoPath {
904 RepoPath {
905 namespace: namespace.to_owned(),
906 name: name.to_owned(),
907 }
908 }
909
910 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
911 AgentScope {
912 repo: path("acme", "rocket"),
913 operations: operations_for(kind, usage)
914 .into_iter()
915 .map(str::to_owned)
916 .collect(),
917 run: Some(RunBinding {
918 kind,
919 usage,
920 run_id: Some("run_1".to_owned()),
921 number: Some(7),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent922 agent: "g1t".to_owned(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily923 system: false,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API924 read: vec![path("acme", "rocket")],
925 push: match kind {
926 RunCredentialKind::Implement
927 | RunCredentialKind::Revise
928 | RunCredentialKind::Answer => vec![GitGrant {
929 repo: path("pulls", "pul_7"),
930 branch: None,
931 }],
932 RunCredentialKind::Update => vec![GitGrant {
933 repo: path("acme", "rocket"),
934 branch: Some("fix-login".to_owned()),
935 }],
936 _ => vec![],
937 },
938 }),
939 }
940 }
941
942 fn agent(member_of: &[&str], scope: AgentScope) -> User {
943 User {
944 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-agent945 username: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API946 kind: PrincipalKind::Agent,
947 verified: true,
948 workspaces: member_of
949 .iter()
950 .map(|slug| Membership::member(*slug))
951 .collect(),
952 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look953 grants: Vec::new(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step954 token: None,
Merge main (membership, two-factor, GitHub repo roles) into tokens955 held: Vec::new(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API956 acting: Some(Box::new(Acting {
957 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-agent958 agent: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API959 on_behalf_of: Principal {
960 id: "usr_1".to_owned(),
961 username: "syntaqx".to_owned(),
962 },
963 scope,
964 })),
965 }
966 }
967
968 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
969 let scope = scope(kind, usage);
970 let user = agent(&["acme"], scope.clone());
971 decide_operation(
972 &user,
973 &scope,
974 operation,
975 Some(&path("acme", "rocket")),
976 true,
977 Some(7),
978 )
979 }
980
981 use CredentialUse::{Runner, Tools};
982 use RunCredentialKind as K;
983
984 /// Which operations each kind of run may use through its tools: the
985 /// allowed and denied matrix.
986 #[test]
987 fn tools_matrix() {
988 let cases: [(&str, [bool; 6]); 12] = [
989 // implement revise answer review plan checks
990 ("get_issue", [true, true, true, true, true, false]),
991 ("create_issue", [true, true, true, false, true, false]),
992 ("add_comment", [true, true, true, true, false, false]),
993 (
994 "review_pull_request",
995 [false, false, false, true, false, false],
996 ),
997 ("remember", [true, true, true, false, false, false]),
998 ("take_messages", [true, true, true, false, false, false]),
999 ("record_session", [false, false, false, false, false, false]),
1000 (
1001 "merge_pull_request",
1002 [false, false, false, false, false, false],
1003 ),
1004 (
1005 "update_repo_settings",
1006 [false, false, false, false, false, false],
1007 ),
1008 ("create_webhook", [false, false, false, false, false, false]),
1009 (
1010 "set_actions_secret",
1011 [false, false, false, false, false, false],
1012 ),
1013 ("assign_issue", [false, false, false, false, false, false]),
1014 ];
1015 let kinds = [
1016 K::Implement,
1017 K::Revise,
1018 K::Answer,
1019 K::Review,
1020 K::Plan,
1021 K::Checks,
1022 ];
1023 for (operation, expected) in cases {
1024 for (kind, allowed) in kinds.into_iter().zip(expected) {
1025 assert_eq!(
1026 op(kind, Tools, operation).allowed,
1027 allowed,
1028 "{operation} by a {} run's tools",
1029 kind.as_str()
1030 );
1031 }
1032 }
1033 }
1034
1035 #[test]
1036 fn runner_matrix() {
1037 assert!(op(K::Implement, Runner, "record_session").allowed);
1038 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
1039 assert!(op(K::Revise, Runner, "record_session").allowed);
1040 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
1041 assert!(!op(K::Implement, Runner, "create_issue").allowed);
1042 assert!(!op(K::Review, Runner, "record_session").allowed);
1043 assert!(!op(K::Checks, Runner, "get_issue").allowed);
1044 }
1045
1046 #[test]
1047 fn settings_billing_tokens_and_members_are_never_reachable() {
1048 for kind in RunCredentialKind::ALL {
1049 for usage in [Runner, Tools] {
1050 for operation in NEVER.iter().copied() {
1051 let decision = op(kind, usage, operation);
1052 assert!(!decision.allowed);
1053 assert_eq!(decision.rule, "never");
1054 }
1055 }
1056 }
1057 // Even a scope that lists one is refused.
1058 let mut wide = scope(K::Implement, Tools);
1059 wide.operations.push("merge_pull_request".to_owned());
1060 let user = agent(&["acme"], wide.clone());
1061 let decision = decide_operation(
1062 &user,
1063 &wide,
1064 "merge_pull_request",
1065 Some(&path("acme", "rocket")),
1066 true,
1067 Some(7),
1068 );
1069 assert_eq!(decision.rule, "never");
1070 }
1071
1072 #[test]
1073 fn another_repository_is_refused() {
1074 let scope = scope(K::Implement, Tools);
1075 let user = agent(&["acme"], scope.clone());
1076 let decision = decide_operation(
1077 &user,
1078 &scope,
1079 "create_issue",
1080 Some(&path("acme", "other")),
1081 true,
1082 None,
1083 );
1084 assert!(!decision.allowed);
1085 assert_eq!(decision.rule, "scope:repository");
1086 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1087 assert_eq!(decision.rule, "scope:repository");
1088 // The repository's name is matched without regard to case.
1089 let decision = decide_operation(
1090 &user,
1091 &scope,
1092 "create_issue",
1093 Some(&path("Acme", "Rocket")),
1094 true,
1095 None,
1096 );
1097 assert!(decision.allowed);
1098 assert_eq!(decision.rule, "run:implement/tools");
1099 }
1100
1101 #[test]
1102 fn the_permission_is_the_intersection_with_the_person() {
1103 let scope = scope(K::Implement, Tools);
1104 // The person left the workspace: their agent can do nothing there.
1105 let user = agent(&[], scope.clone());
1106 let decision = decide_operation(
1107 &user,
1108 &scope,
1109 "get_issue",
1110 Some(&path("acme", "rocket")),
1111 true,
1112 Some(1),
1113 );
1114 assert!(!decision.allowed);
1115 assert_eq!(decision.rule, "on-behalf-of:membership");
1116 // And an owner's agent is only ever a member.
1117 let owner = vec![
1118 Membership {
1119 slug: "acme".to_owned(),
1120 role: Role::Owner,
1121 name: None,
1122 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1123 base_permission: Some(BasePermission::None),
Merge branch 'worktree-agent-ad7c6d88d93adc817'1124 team_creation: None,
Merge main (membership, two-factor, GitHub repo roles) into tokens1125 org_roles: vec![crate::OrgRole::SecurityManager],
1126 privileges: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1127 },
1128 Membership::member("elsewhere"),
1129 ];
1130 let memberships = intersect(&owner, "Acme");
1131 assert_eq!(memberships.len(), 1);
1132 assert_eq!(memberships[0].slug, "acme");
1133 assert_eq!(memberships[0].role, Role::Member);
Merge main (membership, two-factor, GitHub repo roles) into tokens1134 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 API1135 assert!(intersect(&owner, "nowhere").is_empty());
1136 }
1137
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1138 /// An agent gets at most the person's role on the repository, and
1139 /// never more than Write; nothing outside the run's workspace.
1140 #[test]
1141 fn an_agent_has_at_most_its_persons_role() {
1142 use crate::access::{Capability, RepoRef, can, permission};
1143 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1144 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1145 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1146 let tools = scope(K::Implement, Tools);
1147 let scope = scope(K::Implement, Runner);
1148 // An owner's agent: Write, never Admin.
1149 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1150 let mut agent_user = agent(&[], scope.clone());
1151 agent_user.workspaces = intersect(&owner, "acme");
1152 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1153 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1154 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1155 // A member whose workspace gives Read: Read, so it cannot push.
1156 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1157 agent_user.workspaces = intersect(&reader, "acme");
1158 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1159 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1160 // An outside collaborator with Maintain on one repository: Write
1161 // there, nothing elsewhere, and the run is allowed.
1162 let grants = [
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1163 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1164 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 look1165 ];
1166 agent_user.workspaces = intersect(&[], "acme");
1167 agent_user.grants = intersect_grants(&grants, "Acme");
1168 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1169 assert_eq!(permission(Some(&agent_user), other), None);
1170 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1171 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1172 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1173 // The person, downstream of a runner's credential, carries the same.
1174 let person = as_person(&agent_user).expect("a runner acts as the person");
1175 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1176 }
1177
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1178 #[test]
1179 fn a_runner_changes_only_its_own_pull_request() {
1180 let scope = scope(K::Implement, Runner);
1181 let user = agent(&["acme"], scope.clone());
1182 let repo = path("acme", "rocket");
1183 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1184 assert!(!other.allowed);
1185 assert_eq!(other.rule, "scope:pull");
1186 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1187 assert!(own.allowed);
1188 // Reading another is fine.
1189 assert!(
1190 decide_operation(
1191 &user,
1192 &scope,
1193 "get_pull_request",
1194 Some(&repo),
1195 true,
1196 Some(8)
1197 )
1198 .allowed
1199 );
1200 }
1201
1202 #[test]
1203 fn git_matrix() {
1204 let fork = path("pulls", "pul_7");
1205 let upstream = path("acme", "rocket");
1206 let elsewhere = path("acme", "billing");
1207 let implement = scope(K::Implement, Runner);
1208 assert!(decide_git(&implement, &fork, true).allowed);
1209 assert!(decide_git(&implement, &fork, false).allowed);
1210 assert!(decide_git(&implement, &upstream, false).allowed);
1211 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1212 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1213 let review = scope(K::Review, Runner);
1214 assert!(decide_git(&review, &upstream, false).allowed);
1215 assert!(!decide_git(&review, &upstream, true).allowed);
1216 assert!(!decide_git(&review, &fork, true).allowed);
1217 // A tools token made before run credentials never reaches git.
1218 let old = AgentScope {
1219 repo: upstream.clone(),
1220 operations: vec!["get_issue".to_owned()],
1221 run: None,
1222 };
1223 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1224 // Nor does an agent's tools token.
1225 assert_eq!(
1226 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1227 "git:not-a-run"
1228 );
1229 }
1230
1231 #[test]
1232 fn a_push_moves_only_granted_branches() {
1233 let update = scope(K::Update, Runner);
1234 let repo = path("acme", "rocket");
1235 let refs = |names: &[&str]| {
1236 names
1237 .iter()
1238 .map(|name| (*name).to_owned())
1239 .collect::<Vec<_>>()
1240 };
1241 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1242 assert_eq!(
1243 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1244 "git:ref"
1245 );
1246 assert_eq!(
1247 decide_refs(
1248 &update,
1249 &repo,
1250 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1251 )
1252 .rule,
1253 "git:ref"
1254 );
1255 let implement = scope(K::Implement, Runner);
1256 assert!(
1257 decide_refs(
1258 &implement,
1259 &path("pulls", "pul_7"),
1260 &refs(&["refs/heads/main"])
1261 )
1262 .allowed
1263 );
1264 }
1265
1266 #[test]
1267 fn a_runner_acts_downstream_as_the_person() {
1268 let user = agent(&["acme"], scope(K::Implement, Runner));
1269 let person = as_person(&user).unwrap();
1270 assert_eq!(person.id, "usr_1");
1271 assert_eq!(person.username, "syntaqx");
1272 assert_eq!(person.kind, PrincipalKind::User);
1273 assert!(person.is_member("acme"));
1274 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-agent1275 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 API1276 // The tools act as the agent.
1277 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1278 }
1279
1280 #[test]
1281 fn scopes_without_a_run_still_parse() {
1282 let old: AgentScope = serde_json::from_str(
1283 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1284 )
1285 .unwrap();
1286 assert!(old.run.is_none());
1287 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1288 assert!(written.contains(r#""use":"tools""#));
1289 assert!(written.contains(r#""kind":"review""#));
1290 let back: AgentScope = serde_json::from_str(&written).unwrap();
1291 assert_eq!(back.run.unwrap().kind, K::Review);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1292 // Only g1t's own runs say so; every other reads as not.
1293 assert!(!written.contains("system"));
1294 assert!(!back_run(&written).system);
1295 let mut own = scope(K::Bump, Runner);
1296 own.run.as_mut().unwrap().system = true;
1297 let written = serde_json::to_string(&own).unwrap();
1298 assert!(written.contains(r#""system":true"#));
1299 assert!(back_run(&written).system);
1300 }
1301
1302 fn back_run(written: &str) -> RunBinding {
1303 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 API1304 }
1305}

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