Skip to content
1,286 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",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look329 "transfer_repo",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API330 "create_repo",
331 "update_repo",
Merge branch 'main' into worktree-agent-a69aeabc4b0deeb97332 "update_project",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look333 "delete_repo",
334 "list_deleted_repos",
335 "restore_repo",
336 "purge_repo",
337 "rename_repo",
338 "archive_repo",
339 "unarchive_repo",
340 "set_repo_visibility",
341 "rename_branch",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API342 "update_repo_settings",
343 "merge_pull_request",
344 "assign_issue",
345 "plan_work",
346 "apply_plan",
347 "import_issue",
348 "list_integrations",
349 "connect_integration",
AI Gateway: OpenAI's format, open models, and your own providers350 "update_integration",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API351 "disconnect_integration",
352 "test_integration",
353 "get_model_routes",
354 "set_model_routes",
355 "list_webhooks",
356 "create_webhook",
357 "update_webhook",
358 "delete_webhook",
359 "ping_webhook",
360 "list_webhook_deliveries",
361 "redeliver_webhook",
362 "dispatch_workflow",
363 "cancel_workflow_run",
364 "rerun_workflow_run",
365 "update_workflow",
Merge branch 'worktree-agent-a3abfcce648e87dca'366 // Nor lets runs or deployments through, or changes what holds them.
367 "approve_workflow_run",
368 "review_pending_deployments",
369 "update_environment",
370 "delete_environment",
371 "set_workflow_permissions",
372 "set_fork_pr_approval",
373 "create_repository_dispatch",
374 "set_workspace_workflow_permissions",
Merge checks: statuses and check runs on every commit375 // An agent never reports checks on its own work, nor asks for them
376 // to run again: what checks say is the integrations' to say.
377 "create_commit_status",
378 "create_check_run",
379 "update_check_run",
380 "rerequest_check_run",
381 "rerequest_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API382 "list_actions_secrets",
383 "set_actions_secret",
384 "delete_actions_secret",
385 "list_actions_variables",
386 "set_actions_variable",
387 "delete_actions_variable",
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look388 "list_collaborators",
389 "get_collaborator_permission",
390 "add_collaborator",
391 "update_collaborator",
392 "remove_collaborator",
393 "list_repo_invitations",
394 "revoke_repo_invitation",
395 "list_my_repo_invitations",
396 "accept_repo_invitation",
397 "decline_repo_invitation",
398 "set_base_permission",
399 "list_outside_collaborators",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar400 // Teams: who is in which, and what they reach, is for people.
401 "create_team",
402 "update_team",
403 "delete_team",
404 "set_team_member",
405 "remove_team_member",
406 "set_team_repo",
407 "remove_team_repo",
408 "set_team_review_assignment",
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily409 // Dismissing a secret lets it through push protection.
410 "dismiss_security_alert",
411 "reopen_security_alert",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar412 // Nor any other decision about security: closing or reopening an
413 // alert, pushing past push protection or deciding who may, changing
414 // what is looked for or when checks fail, or putting more agents to
415 // work. An agent fixes what it finds in its own pull request.
416 "update_secret_scanning_alert",
417 "bypass_push_protection",
418 "review_bypass_request",
419 "create_custom_pattern",
420 "update_custom_pattern",
421 "delete_custom_pattern",
422 "update_code_scanning_alert",
423 "update_vulnerability_alert",
424 "fix_security_alert",
425 "update_security_settings",
426 "update_workspace_security_settings",
API: notifications over REST and MCP, with notifications scopes427 // A person's own inbox: g1t's agents act as g1t, which has none.
428 "list_notifications",
429 "get_notification_thread",
430 "mark_notifications_read",
431 "mark_thread_read",
432 "mark_thread_done",
433 "save_thread",
434 "snooze_thread",
435 "get_thread_subscription",
436 "set_thread_subscription",
437 "delete_thread_subscription",
438 "get_repo_subscription",
439 "set_repo_subscription",
440 "delete_repo_subscription",
441 "list_watched_repos",
API: pinned projects over REST and MCP442 // Pins are a person's own, as the inbox is.
443 "list_pinned_projects",
444 "pin_project",
445 "unpin_project",
446 "reorder_pinned_projects",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API447];
448
449/// Reading what an agent needs to know about its repository.
450const TOOLS_READ: &[&str] = &[
451 "get_repo",
452 "list_issues",
453 "get_issue",
454 "list_labels",
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar455 "list_issue_labels",
456 "list_milestones",
457 "get_milestone",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API458 "list_pull_requests",
459 "get_pull_request",
460 "get_pull_request_changes",
461 "read_session",
462 "get_merge_queue",
463 "list_events",
464 "recall",
465 "search_context",
466 "get_entity",
Search across all of g1t, Explore, and a command palette467 "search",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API468 "list_workflows",
469 "list_workflow_runs",
470 "get_workflow_run",
471 "get_job_logs",
Merge branch 'worktree-agent-a3abfcce648e87dca'472 "get_pending_deployments",
473 "get_workflow_permissions",
474 "get_fork_pr_approval",
Merge checks: statuses and check runs on every commit475 "list_commit_statuses",
476 "get_combined_status",
477 "list_check_runs_for_ref",
478 "get_check_run",
479 "list_check_run_annotations",
480 "list_check_suites_for_ref",
481 "get_check_suite",
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API482];
483
484pub fn is_read(operation: &str) -> bool {
485 READ_OPERATIONS.contains(&operation)
486}
487
488/// The API and MCP operations a run of `kind` may use with a credential
489/// for `usage`. Git is separate: see [`decide_git`].
490pub fn operations_for(kind: RunCredentialKind, usage: CredentialUse) -> Vec<&'static str> {
491 use RunCredentialKind as K;
492 let mut operations: Vec<&'static str> = Vec::new();
493 match usage {
494 CredentialUse::Runner => {
495 if kind.works_on_a_pull() {
496 operations.extend(["get_repo", "get_pull_request", "record_session"]);
497 }
498 if kind == K::Implement {
499 operations.push("mark_pull_request_ready");
500 }
501 }
502 CredentialUse::Tools => match kind {
503 K::Implement | K::Revise | K::Answer => {
504 operations.extend(TOOLS_READ.iter().copied());
505 operations.extend([
506 "create_issue",
507 "add_comment",
508 "take_messages",
509 "remember",
510 "message_agent",
511 "answer_message",
512 "get_context",
513 ]);
514 }
515 K::Review => {
516 operations.extend(TOOLS_READ.iter().copied());
517 operations.extend(["add_comment", "review_pull_request", "get_context"]);
518 }
519 K::Plan => {
520 operations.extend(TOOLS_READ.iter().copied());
521 operations.extend(["create_issue", "get_context"]);
522 }
523 K::Update => operations.extend(TOOLS_READ.iter().copied()),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily524 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 API525 },
526 }
527 operations
528}
529
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step530/// What a run's credential may do, in the scope vocabulary that access
531/// tokens use (see [`crate::scopes`]): the scopes of its operations, and
532/// for a runner, git's. Its operations, its repository and its run still
533/// bound it more tightly than these scopes say.
534pub fn run_scopes(kind: RunCredentialKind, usage: CredentialUse) -> Vec<crate::scopes::Scope> {
535 use crate::scopes::{Scope, normalize, scope_for};
536 let mut scopes: Vec<Scope> = operations_for(kind, usage)
537 .into_iter()
538 .filter_map(scope_for)
539 .collect();
540 if usage == CredentialUse::Runner {
541 scopes.push(Scope::CodeRead);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily542 if matches!(
543 kind,
544 RunCredentialKind::Implement
545 | RunCredentialKind::Revise
546 | RunCredentialKind::Answer
547 | RunCredentialKind::Update
548 | RunCredentialKind::Bump
549 ) {
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step550 scopes.push(Scope::CodeWrite);
551 }
552 }
553 normalize(&mut scopes);
554 scopes
555}
556
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API557/// Operations that change a pull request, which a runner may do only to
558/// the pull request its run works on.
559const PULL_WRITES: &[&str] = &["record_session", "mark_pull_request_ready"];
560
561/// Whether something was allowed, and the rule that decided it.
562#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
563pub struct Decision {
564 pub allowed: bool,
565 /// A short, stable name: `run:implement/tools`, `never`,
566 /// `scope:repository` and so on. Shown in the audit log.
567 pub rule: String,
568 /// Why it was refused, for the caller.
569 #[serde(default, skip_serializing_if = "Option::is_none")]
570 pub reason: Option<String>,
571}
572
573impl Decision {
574 pub fn allow(rule: impl Into<String>) -> Self {
575 Decision {
576 allowed: true,
577 rule: rule.into(),
578 reason: None,
579 }
580 }
581
582 pub fn deny(rule: impl Into<String>, reason: impl Into<String>) -> Self {
583 Decision {
584 allowed: false,
585 rule: rule.into(),
586 reason: Some(reason.into()),
587 }
588 }
589}
590
591fn same_repo(a: &RepoPath, b: &RepoPath) -> bool {
592 a.namespace.eq_ignore_ascii_case(&b.namespace) && a.name.eq_ignore_ascii_case(&b.name)
593}
594
595fn scope_rule(scope: &AgentScope) -> String {
596 match &scope.run {
597 Some(run) => format!("run:{}/{}", run.kind.as_str(), run.usage.as_str()),
598 None => "agent-token".to_owned(),
599 }
600}
601
602/// Whether `user`, resolved from an agent's token with `scope`, may use
603/// `operation`. `repo` is the repository the call names, if any, and
604/// `needs_repo` whether the operation is about one; `number` the issue or
605/// pull request it names.
606pub fn decide_operation(
607 user: &User,
608 scope: &AgentScope,
609 operation: &str,
610 repo: Option<&RepoPath>,
611 needs_repo: bool,
612 number: Option<u32>,
613) -> Decision {
614 let who = "A g1t agent's token";
615 if NEVER.contains(&operation) {
616 return Decision::deny(
617 "never",
618 format!(
619 "{who} can never use {operation}: settings, members, tokens, billing, integrations, webhooks, secrets and merging are for people."
620 ),
621 );
622 }
623 if !scope.operations.iter().any(|name| name == operation) {
624 return Decision::deny(
625 "scope:operation",
626 format!("{who} for this run cannot use {operation}."),
627 );
628 }
629 if needs_repo && !repo.is_some_and(|asked| same_repo(asked, &scope.repo)) {
630 return Decision::deny(
631 "scope:repository",
632 format!(
633 "{who} works in {}/{} only.",
634 scope.repo.namespace, scope.repo.name
635 ),
636 );
637 }
638 // 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 look639 // in the repository's workspace, as a member or with a role on its
640 // repositories. What it may do in the repository itself is their
641 // role there, which services check (`access::can`).
642 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 API643 return Decision::deny(
644 "on-behalf-of:membership",
645 format!(
646 "The person this agent works for is no longer a member of {}.",
647 scope.repo.namespace
648 ),
649 );
650 }
651 if let Some(run) = &scope.run
652 && run.usage == CredentialUse::Runner
653 && PULL_WRITES.contains(&operation)
654 && run.number.is_some()
655 && number != run.number
656 {
657 return Decision::deny(
658 "scope:pull",
659 format!(
660 "{who} can change pull request #{} only.",
661 run.number.unwrap_or_default()
662 ),
663 );
664 }
665 Decision::allow(scope_rule(scope))
666}
667
668/// Whether a run credential may clone or fetch (`write` false), or push to
669/// (`write` true), the repository at `repo`.
670pub fn decide_git(scope: &AgentScope, repo: &RepoPath, write: bool) -> Decision {
671 let Some(run) = scope
672 .run
673 .as_ref()
674 .filter(|run| run.usage == CredentialUse::Runner)
675 else {
676 return Decision::deny(
677 "git:not-a-run",
678 "A g1t agent's tools token cannot be used with git.",
679 );
680 };
681 let pushable = run.push.iter().any(|grant| same_repo(&grant.repo, repo));
682 if write {
683 return if pushable {
684 Decision::allow(format!("{}:push", scope_rule(scope)))
685 } else {
686 Decision::deny(
687 "git:push",
688 format!(
689 "A {} run cannot push to {}/{}.",
690 run.kind.as_str(),
691 repo.namespace,
692 repo.name
693 ),
694 )
695 };
696 }
697 let readable = pushable
698 || same_repo(&scope.repo, repo)
699 || run.read.iter().any(|path| same_repo(path, repo));
700 if readable {
701 Decision::allow(format!("{}:read", scope_rule(scope)))
702 } else {
703 Decision::deny(
704 "git:read",
705 format!(
706 "A {} run cannot read {}/{}.",
707 run.kind.as_str(),
708 repo.namespace,
709 repo.name
710 ),
711 )
712 }
713}
714
715/// Whether a push to `repo` is limited to certain branches, so that the
716/// refs it moves have to be read and checked with [`decide_refs`].
717pub fn limits_branches(scope: &AgentScope, repo: &RepoPath) -> bool {
718 scope
719 .run
720 .iter()
721 .flat_map(|run| run.push.iter())
722 .any(|grant| same_repo(&grant.repo, repo) && grant.branch.is_some())
723}
724
725/// Whether a push to `repo` may move `refs` (full refs, such as
726/// `refs/heads/main`). Tags are never a run's to move.
727pub fn decide_refs(scope: &AgentScope, repo: &RepoPath, refs: &[String]) -> Decision {
728 let repo_decision = decide_git(scope, repo, true);
729 if !repo_decision.allowed {
730 return repo_decision;
731 }
732 let grants: Vec<&GitGrant> = scope
733 .run
734 .iter()
735 .flat_map(|run| run.push.iter())
736 .filter(|grant| same_repo(&grant.repo, repo))
737 .collect();
738 for git_ref in refs {
739 let Some(branch) = git_ref.strip_prefix("refs/heads/") else {
740 return Decision::deny("git:ref", format!("A run cannot push {git_ref}."));
741 };
742 let allowed = grants
743 .iter()
744 .any(|grant| grant.branch.as_deref().is_none_or(|only| only == branch));
745 if !allowed {
746 return Decision::deny(
747 "git:ref",
748 format!(
749 "A run cannot push to {branch} in {}/{}.",
750 repo.namespace, repo.name
751 ),
752 );
753 }
754 }
755 repo_decision
756}
757
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look758/// The most an agent may be on a repository, whoever it works for: it
759/// can push, merge and run, never change settings or who has access.
760pub const AGENT_CEILING: RepoRole = RepoRole::Write;
761
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API762/// 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 look763/// workspace, as a member, only if the person is in it now, with the
764/// person's role on its repositories (an owner's Admin included) cut down
765/// to [`AGENT_CEILING`].
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API766pub fn intersect(person: &[Membership], namespace: &str) -> Vec<Membership> {
767 let namespace = namespace.to_lowercase();
768 person
769 .iter()
770 .filter(|membership| membership.slug == namespace)
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look771 .map(|membership| {
772 let base = match membership.role {
773 Role::Owner => BasePermission::Admin,
774 Role::Member => membership.base_permission.unwrap_or_default(),
775 };
776 Membership {
777 role: Role::Member,
778 base_permission: Some(match base {
779 BasePermission::Admin => BasePermission::Write,
780 base => base,
781 }),
782 ..membership.clone()
783 }
784 })
785 .collect()
786}
787
788/// The repository grants an agent working for `person` has: those in the
789/// run's workspace, each cut down to [`AGENT_CEILING`].
790pub fn intersect_grants(person: &[RepoGrant], namespace: &str) -> Vec<RepoGrant> {
791 let namespace = namespace.to_lowercase();
792 person
793 .iter()
794 .filter(|grant| grant.workspace == namespace)
795 .map(|grant| RepoGrant {
796 role: grant.role.min(AGENT_CEILING),
797 ..grant.clone()
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API798 })
799 .collect()
800}
801
802/// Who a runner's credential acts as downstream: the person, with only the
803/// agent's (already intersected) memberships. `None` for anything else.
804pub fn as_person(user: &User) -> Option<User> {
805 let acting = user.acting.as_ref()?;
806 if user.kind != PrincipalKind::Agent {
807 return None;
808 }
809 let run = acting.run()?;
810 if run.usage != CredentialUse::Runner {
811 return None;
812 }
813 Some(User {
814 id: acting.on_behalf_of.id.clone(),
815 username: acting.on_behalf_of.username.clone(),
816 kind: PrincipalKind::User,
817 verified: user.verified,
818 workspaces: user.workspaces.clone(),
819 avatar: None,
820 acting: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look821 grants: user.grants.clone(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step822 token: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API823 })
824}
825
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent826/// 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 API827pub fn describe(user: &User) -> String {
828 match &user.acting {
829 Some(acting) => format!(
830 "{} on behalf of {}",
831 acting.agent, acting.on_behalf_of.username
832 ),
833 None => user.username.clone(),
834 }
835}
836
837#[cfg(test)]
838mod tests {
839 use super::*;
840
841 #[test]
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step842 fn a_run_s_scopes_are_never_admin() {
843 for kind in RunCredentialKind::ALL {
844 for usage in [CredentialUse::Runner, CredentialUse::Tools] {
845 let scopes = run_scopes(kind, usage);
846 assert!(scopes.iter().all(|scope| !scope.dangerous()), "{kind:?} {usage:?}: {scopes:?}");
847 }
848 }
849 let review = run_scopes(RunCredentialKind::Review, CredentialUse::Tools);
850 assert!(review.contains(&crate::scopes::Scope::PullRequestsWrite));
851 assert!(!review.contains(&crate::scopes::Scope::CodeWrite));
852 }
853
854 #[test]
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API855 fn agents_can_search_the_context_hub() {
856 for kind in [RunCredentialKind::Implement, RunCredentialKind::Review, RunCredentialKind::Plan] {
857 let tools = operations_for(kind, CredentialUse::Tools);
858 assert!(tools.contains(&"search_context") && tools.contains(&"get_entity"));
859 }
860 assert!(is_read("search_context") && is_read("get_entity"));
861 }
862
Search across all of g1t, Explore, and a command palette863 #[test]
864 fn agents_can_search_all_of_g1t() {
865 // Site-wide search only reads: every run that reads its repository
866 // may use it, and nothing that never reads gets it.
867 assert!(is_read("search"));
868 assert!(!NEVER.contains(&"search"));
869 for kind in [
870 RunCredentialKind::Implement,
871 RunCredentialKind::Revise,
872 RunCredentialKind::Answer,
873 RunCredentialKind::Review,
874 RunCredentialKind::Plan,
875 RunCredentialKind::Update,
876 ] {
877 let tools = operations_for(kind, CredentialUse::Tools);
878 assert!(tools.contains(&"search"), "{kind:?} should search");
879 // The context hub's search stays its own tool beside it.
880 assert!(tools.contains(&"search_context"), "{kind:?} keeps search_context");
881 }
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily882 for kind in [RunCredentialKind::Checks, RunCredentialKind::Queue, RunCredentialKind::Mergecheck, RunCredentialKind::Deploy, RunCredentialKind::Bump] {
Search across all of g1t, Explore, and a command palette883 assert!(!operations_for(kind, CredentialUse::Tools).contains(&"search"));
884 }
885 assert!(!operations_for(RunCredentialKind::Implement, CredentialUse::Runner).contains(&"search"));
886 }
887
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API888 fn path(namespace: &str, name: &str) -> RepoPath {
889 RepoPath {
890 namespace: namespace.to_owned(),
891 name: name.to_owned(),
892 }
893 }
894
895 fn scope(kind: RunCredentialKind, usage: CredentialUse) -> AgentScope {
896 AgentScope {
897 repo: path("acme", "rocket"),
898 operations: operations_for(kind, usage)
899 .into_iter()
900 .map(str::to_owned)
901 .collect(),
902 run: Some(RunBinding {
903 kind,
904 usage,
905 run_id: Some("run_1".to_owned()),
906 number: Some(7),
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent907 agent: "g1t".to_owned(),
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily908 system: false,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API909 read: vec![path("acme", "rocket")],
910 push: match kind {
911 RunCredentialKind::Implement
912 | RunCredentialKind::Revise
913 | RunCredentialKind::Answer => vec![GitGrant {
914 repo: path("pulls", "pul_7"),
915 branch: None,
916 }],
917 RunCredentialKind::Update => vec![GitGrant {
918 repo: path("acme", "rocket"),
919 branch: Some("fix-login".to_owned()),
920 }],
921 _ => vec![],
922 },
923 }),
924 }
925 }
926
927 fn agent(member_of: &[&str], scope: AgentScope) -> User {
928 User {
929 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-agent930 username: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API931 kind: PrincipalKind::Agent,
932 verified: true,
933 workspaces: member_of
934 .iter()
935 .map(|slug| Membership::member(*slug))
936 .collect(),
937 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look938 grants: Vec::new(),
Thirteen MCP tools and classic token scopes; agents rate their confidence and can be put on an issue in one step939 token: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API940 acting: Some(Box::new(Acting {
941 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-agent942 agent: "g1t".to_owned(),
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API943 on_behalf_of: Principal {
944 id: "usr_1".to_owned(),
945 username: "syntaqx".to_owned(),
946 },
947 scope,
948 })),
949 }
950 }
951
952 fn op(kind: RunCredentialKind, usage: CredentialUse, operation: &str) -> Decision {
953 let scope = scope(kind, usage);
954 let user = agent(&["acme"], scope.clone());
955 decide_operation(
956 &user,
957 &scope,
958 operation,
959 Some(&path("acme", "rocket")),
960 true,
961 Some(7),
962 )
963 }
964
965 use CredentialUse::{Runner, Tools};
966 use RunCredentialKind as K;
967
968 /// Which operations each kind of run may use through its tools: the
969 /// allowed and denied matrix.
970 #[test]
971 fn tools_matrix() {
972 let cases: [(&str, [bool; 6]); 12] = [
973 // implement revise answer review plan checks
974 ("get_issue", [true, true, true, true, true, false]),
975 ("create_issue", [true, true, true, false, true, false]),
976 ("add_comment", [true, true, true, true, false, false]),
977 (
978 "review_pull_request",
979 [false, false, false, true, false, false],
980 ),
981 ("remember", [true, true, true, false, false, false]),
982 ("take_messages", [true, true, true, false, false, false]),
983 ("record_session", [false, false, false, false, false, false]),
984 (
985 "merge_pull_request",
986 [false, false, false, false, false, false],
987 ),
988 (
989 "update_repo_settings",
990 [false, false, false, false, false, false],
991 ),
992 ("create_webhook", [false, false, false, false, false, false]),
993 (
994 "set_actions_secret",
995 [false, false, false, false, false, false],
996 ),
997 ("assign_issue", [false, false, false, false, false, false]),
998 ];
999 let kinds = [
1000 K::Implement,
1001 K::Revise,
1002 K::Answer,
1003 K::Review,
1004 K::Plan,
1005 K::Checks,
1006 ];
1007 for (operation, expected) in cases {
1008 for (kind, allowed) in kinds.into_iter().zip(expected) {
1009 assert_eq!(
1010 op(kind, Tools, operation).allowed,
1011 allowed,
1012 "{operation} by a {} run's tools",
1013 kind.as_str()
1014 );
1015 }
1016 }
1017 }
1018
1019 #[test]
1020 fn runner_matrix() {
1021 assert!(op(K::Implement, Runner, "record_session").allowed);
1022 assert!(op(K::Implement, Runner, "mark_pull_request_ready").allowed);
1023 assert!(op(K::Revise, Runner, "record_session").allowed);
1024 assert!(!op(K::Revise, Runner, "mark_pull_request_ready").allowed);
1025 assert!(!op(K::Implement, Runner, "create_issue").allowed);
1026 assert!(!op(K::Review, Runner, "record_session").allowed);
1027 assert!(!op(K::Checks, Runner, "get_issue").allowed);
1028 }
1029
1030 #[test]
1031 fn settings_billing_tokens_and_members_are_never_reachable() {
1032 for kind in RunCredentialKind::ALL {
1033 for usage in [Runner, Tools] {
1034 for operation in NEVER.iter().copied() {
1035 let decision = op(kind, usage, operation);
1036 assert!(!decision.allowed);
1037 assert_eq!(decision.rule, "never");
1038 }
1039 }
1040 }
1041 // Even a scope that lists one is refused.
1042 let mut wide = scope(K::Implement, Tools);
1043 wide.operations.push("merge_pull_request".to_owned());
1044 let user = agent(&["acme"], wide.clone());
1045 let decision = decide_operation(
1046 &user,
1047 &wide,
1048 "merge_pull_request",
1049 Some(&path("acme", "rocket")),
1050 true,
1051 Some(7),
1052 );
1053 assert_eq!(decision.rule, "never");
1054 }
1055
1056 #[test]
1057 fn another_repository_is_refused() {
1058 let scope = scope(K::Implement, Tools);
1059 let user = agent(&["acme"], scope.clone());
1060 let decision = decide_operation(
1061 &user,
1062 &scope,
1063 "create_issue",
1064 Some(&path("acme", "other")),
1065 true,
1066 None,
1067 );
1068 assert!(!decision.allowed);
1069 assert_eq!(decision.rule, "scope:repository");
1070 let decision = decide_operation(&user, &scope, "create_issue", None, true, None);
1071 assert_eq!(decision.rule, "scope:repository");
1072 // The repository's name is matched without regard to case.
1073 let decision = decide_operation(
1074 &user,
1075 &scope,
1076 "create_issue",
1077 Some(&path("Acme", "Rocket")),
1078 true,
1079 None,
1080 );
1081 assert!(decision.allowed);
1082 assert_eq!(decision.rule, "run:implement/tools");
1083 }
1084
1085 #[test]
1086 fn the_permission_is_the_intersection_with_the_person() {
1087 let scope = scope(K::Implement, Tools);
1088 // The person left the workspace: their agent can do nothing there.
1089 let user = agent(&[], scope.clone());
1090 let decision = decide_operation(
1091 &user,
1092 &scope,
1093 "get_issue",
1094 Some(&path("acme", "rocket")),
1095 true,
1096 Some(1),
1097 );
1098 assert!(!decision.allowed);
1099 assert_eq!(decision.rule, "on-behalf-of:membership");
1100 // And an owner's agent is only ever a member.
1101 let owner = vec![
1102 Membership {
1103 slug: "acme".to_owned(),
1104 role: Role::Owner,
1105 name: None,
1106 avatar: None,
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1107 base_permission: Some(BasePermission::None),
Merge branch 'worktree-agent-ad7c6d88d93adc817'1108 team_creation: None,
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1109 },
1110 Membership::member("elsewhere"),
1111 ];
1112 let memberships = intersect(&owner, "Acme");
1113 assert_eq!(memberships.len(), 1);
1114 assert_eq!(memberships[0].slug, "acme");
1115 assert_eq!(memberships[0].role, Role::Member);
1116 assert!(intersect(&owner, "nowhere").is_empty());
1117 }
1118
Invite-only launch: sign in with GitHub, repository access and lifecycle, many emails, a new look1119 /// An agent gets at most the person's role on the repository, and
1120 /// never more than Write; nothing outside the run's workspace.
1121 #[test]
1122 fn an_agent_has_at_most_its_persons_role() {
1123 use crate::access::{Capability, RepoRef, can, permission};
1124 let rocket = RepoRef { id: "rep_1", namespace: "acme", private: true };
1125 let other = RepoRef { id: "rep_2", namespace: "acme", private: true };
1126 let elsewhere = RepoRef { id: "rep_3", namespace: "globex", private: true };
1127 let tools = scope(K::Implement, Tools);
1128 let scope = scope(K::Implement, Runner);
1129 // An owner's agent: Write, never Admin.
1130 let owner = [Membership { role: Role::Owner, ..Membership::member("acme") }, Membership::member("globex")];
1131 let mut agent_user = agent(&[], scope.clone());
1132 agent_user.workspaces = intersect(&owner, "acme");
1133 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1134 assert!(!can(Some(&agent_user), rocket, Capability::ManageSettings));
1135 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1136 // A member whose workspace gives Read: Read, so it cannot push.
1137 let reader = [Membership { base_permission: Some(BasePermission::Read), ..Membership::member("acme") }];
1138 agent_user.workspaces = intersect(&reader, "acme");
1139 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Read));
1140 assert!(!can(Some(&agent_user), rocket, Capability::Push));
1141 // An outside collaborator with Maintain on one repository: Write
1142 // there, nothing elsewhere, and the run is allowed.
1143 let grants = [
Teams and CODEOWNERS, labels and milestones, dependency updates, the security suite, and a clearer top bar1144 RepoGrant { repo_id: "rep_1".into(), workspace: "acme".into(), role: RepoRole::Maintain, team: None },
1145 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 look1146 ];
1147 agent_user.workspaces = intersect(&[], "acme");
1148 agent_user.grants = intersect_grants(&grants, "Acme");
1149 assert_eq!(permission(Some(&agent_user), rocket), Some(RepoRole::Write));
1150 assert_eq!(permission(Some(&agent_user), other), None);
1151 assert_eq!(permission(Some(&agent_user), elsewhere), None);
1152 let decision = decide_operation(&agent_user, &tools, "get_issue", Some(&path("acme", "rocket")), true, Some(1));
1153 assert!(decision.allowed, "{}", decision.reason.unwrap_or_default());
1154 // The person, downstream of a runner's credential, carries the same.
1155 let person = as_person(&agent_user).expect("a runner acts as the person");
1156 assert_eq!(permission(Some(&person), rocket), Some(RepoRole::Write));
1157 }
1158
Agents get guardrails, run credentials, an audit log, a context hub, repository instructions and mentions; security upkeep; snake_case API1159 #[test]
1160 fn a_runner_changes_only_its_own_pull_request() {
1161 let scope = scope(K::Implement, Runner);
1162 let user = agent(&["acme"], scope.clone());
1163 let repo = path("acme", "rocket");
1164 let other = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(8));
1165 assert!(!other.allowed);
1166 assert_eq!(other.rule, "scope:pull");
1167 let own = decide_operation(&user, &scope, "record_session", Some(&repo), true, Some(7));
1168 assert!(own.allowed);
1169 // Reading another is fine.
1170 assert!(
1171 decide_operation(
1172 &user,
1173 &scope,
1174 "get_pull_request",
1175 Some(&repo),
1176 true,
1177 Some(8)
1178 )
1179 .allowed
1180 );
1181 }
1182
1183 #[test]
1184 fn git_matrix() {
1185 let fork = path("pulls", "pul_7");
1186 let upstream = path("acme", "rocket");
1187 let elsewhere = path("acme", "billing");
1188 let implement = scope(K::Implement, Runner);
1189 assert!(decide_git(&implement, &fork, true).allowed);
1190 assert!(decide_git(&implement, &fork, false).allowed);
1191 assert!(decide_git(&implement, &upstream, false).allowed);
1192 assert_eq!(decide_git(&implement, &upstream, true).rule, "git:push");
1193 assert_eq!(decide_git(&implement, &elsewhere, false).rule, "git:read");
1194 let review = scope(K::Review, Runner);
1195 assert!(decide_git(&review, &upstream, false).allowed);
1196 assert!(!decide_git(&review, &upstream, true).allowed);
1197 assert!(!decide_git(&review, &fork, true).allowed);
1198 // A tools token made before run credentials never reaches git.
1199 let old = AgentScope {
1200 repo: upstream.clone(),
1201 operations: vec!["get_issue".to_owned()],
1202 run: None,
1203 };
1204 assert_eq!(decide_git(&old, &upstream, false).rule, "git:not-a-run");
1205 // Nor does an agent's tools token.
1206 assert_eq!(
1207 decide_git(&scope(K::Implement, Tools), &upstream, false).rule,
1208 "git:not-a-run"
1209 );
1210 }
1211
1212 #[test]
1213 fn a_push_moves_only_granted_branches() {
1214 let update = scope(K::Update, Runner);
1215 let repo = path("acme", "rocket");
1216 let refs = |names: &[&str]| {
1217 names
1218 .iter()
1219 .map(|name| (*name).to_owned())
1220 .collect::<Vec<_>>()
1221 };
1222 assert!(decide_refs(&update, &repo, &refs(&["refs/heads/fix-login"])).allowed);
1223 assert_eq!(
1224 decide_refs(&update, &repo, &refs(&["refs/heads/main"])).rule,
1225 "git:ref"
1226 );
1227 assert_eq!(
1228 decide_refs(
1229 &update,
1230 &repo,
1231 &refs(&["refs/heads/fix-login", "refs/tags/v1"])
1232 )
1233 .rule,
1234 "git:ref"
1235 );
1236 let implement = scope(K::Implement, Runner);
1237 assert!(
1238 decide_refs(
1239 &implement,
1240 &path("pulls", "pul_7"),
1241 &refs(&["refs/heads/main"])
1242 )
1243 .allowed
1244 );
1245 }
1246
1247 #[test]
1248 fn a_runner_acts_downstream_as_the_person() {
1249 let user = agent(&["acme"], scope(K::Implement, Runner));
1250 let person = as_person(&user).unwrap();
1251 assert_eq!(person.id, "usr_1");
1252 assert_eq!(person.username, "syntaqx");
1253 assert_eq!(person.kind, PrincipalKind::User);
1254 assert!(person.is_member("acme"));
1255 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-agent1256 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 API1257 // The tools act as the agent.
1258 assert!(as_person(&agent(&["acme"], scope(K::Implement, Tools))).is_none());
1259 }
1260
1261 #[test]
1262 fn scopes_without_a_run_still_parse() {
1263 let old: AgentScope = serde_json::from_str(
1264 r#"{"repo":{"namespace":"acme","name":"rocket"},"operations":["get_issue"]}"#,
1265 )
1266 .unwrap();
1267 assert!(old.run.is_none());
1268 let written = serde_json::to_string(&scope(K::Review, Tools)).unwrap();
1269 assert!(written.contains(r#""use":"tools""#));
1270 assert!(written.contains(r#""kind":"review""#));
1271 let back: AgentScope = serde_json::from_str(&written).unwrap();
1272 assert_eq!(back.run.unwrap().kind, K::Review);
Git storage hardened, pages in tens of milliseconds, honest security alerts, and costs reconciled daily1273 // Only g1t's own runs say so; every other reads as not.
1274 assert!(!written.contains("system"));
1275 assert!(!back_run(&written).system);
1276 let mut own = scope(K::Bump, Runner);
1277 own.run.as_mut().unwrap().system = true;
1278 let written = serde_json::to_string(&own).unwrap();
1279 assert!(written.contains(r#""system":true"#));
1280 assert!(back_run(&written).system);
1281 }
1282
1283 fn back_run(written: &str) -> RunBinding {
1284 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 API1285 }
1286}

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