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

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